DataGridView 单元格只能录入数字

转自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 ;
                }
            }
        }

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值