C# DataGridView 限制单元格输入时遇到的问题

限制单元格输入的实现方法:

添加DataGridView的EditingControlShowing事件,代码如下:

private void DataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
      if(e.Control is DataGridViewTextBoxEditingControl tb)
      {
           DataGridView dgv = sender as DataGridView;

           if (dgv.CurrentCell.ColumnIndex > 0)
           {
               tb.ShortcutsEnabled = false;
               tb.ImeMode = ImeMode.Disable;
               tb.SelectAll();

               tb.KeyPress -= new KeyPressEventHandler(CellEdit_KeyPress);
               tb.KeyPress += new KeyPressEventHandler(CellEdit_KeyPress);
           }
    }
}

软件需求,第一列输入不限制,输入汉字、英文、数字...都可以,第二列必须输入数字。

使用发现,只要激活第二列的单元格后,第一列就只能输入数字了。与实际需求相反

分析,整个DataGridView控件编辑单元格,只用一个DataGridViewTextBoxEditingControl 类型的控件实现输入。因此,激活第一列单元格后添加了限制。以后就被限制了。修改代码如下:

private void CellEdit_KeyPress(object sender, KeyPressEventArgs e)
{
    if (!char.IsDigit(e.KeyChar) &&
        !char.IsControl(e.KeyChar))
    {
        if (e.KeyChar == '.')
        {
            string tempstr = ((TextBox)sender).Text;
            if (tempstr.Length > 0 && tempstr.IndexOf('.') < 0)
            {
                return;
            }
        }
        else if (e.KeyChar == '-')
        {
            TextBox textBox = ((TextBox)sender);
            string tempstr = textBox.Text;
            if (tempstr.Length == 0 || (textBox.SelectionStart == 0 && tempstr.IndexOf('-') < 0))
            {
                return;
            }
        }
        e.Handled = true;
    }
}

private void DataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
    if(e.Control is DataGridViewTextBoxEditingControl tb)
    {
        DataGridView dgv = sender as DataGridView;
        if (dgv.CurrentCell.ColumnIndex > 0)
        {
            tb.ShortcutsEnabled = false;
            tb.ImeMode = ImeMode.Disable;
            tb.SelectAll();

            tb.KeyPress -= new KeyPressEventHandler(CellEdit_KeyPress);
            tb.KeyPress += new KeyPressEventHandler(CellEdit_KeyPress);
        }
        else
        {
            tb.ShortcutsEnabled = true;
            tb.ImeMode = ImeMode.NoControl;
            tb.SelectAll();
            tb.KeyPress -= new KeyPressEventHandler(CellEdit_KeyPress);
        }
    }
}

重新测试OK!

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值