DataGridView 单元格只能录入数字

来源:互联网 发布:慢镜头拍摄软件app 编辑:程序博客网 时间:2024/05/21 07:40

转自http://hi.baidu.com/ruishicun/blog/item/2a1209ec157ae83b27979141.html

 

public DataGridViewTextBoxEditingControl CellEdit = null; // 声明 一个 CellEdit

 

private void datagridyf_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
        {
       
            CellEdit = (DataGridViewTextBoxEditingControl)e.Control; // 赋值
            CellEdit.SelectAll();
            CellEdit.KeyPress += Cells_KeyPress; // 绑定到事件
        }

 

// 自定义事件

 

        private void Cells_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (datagridyf.CurrentCellAddress.X == 2) // 判断当前列是不是要控制的列 我是控制的索引值为2的 列(即第三列)
            {
                if ((Convert.ToInt32(e.KeyChar) < 48 || Convert.ToInt32(e.KeyChar) > 57) && Convert.ToInt32(e.KeyChar) != 46 && Convert.ToInt32(e.KeyChar) != 8 && Convert.ToInt32(e.KeyChar) != 13)
                {
                    e.Handled = true; // 输入非法就屏蔽
                }
                else
                {
                    if ((Convert.ToInt32(e.KeyChar) == 46) && (txtjg.Text.IndexOf(".") != -1))
                    {
                        e.Handled = true;
                    }
                }
            }
        }

 

下面是在输入完成后才验证的 这个主要是在 CellValidating事件中完成

 

private void datagridyf_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
        {
            if (e.ColumnIndex == datagridyf.Columns["Pric"].Index )
            {
                datagridyf.Rows [e.RowIndex].ErrorText ="";
                int NewVal=0;
                if (!int.TryParse (e.FormattedValue.ToString (),out NewVal ) || NewVal <0)
                {
                    e.Cancel=true ;
                    datagridyf.Rows [e.RowIndex].ErrorText ="价格列只能输入数字";
                    return ;
                }
            }
        }