【问题标题】:Check decimal value in DataGridView Cell检查 DataGridView 单元格中的十进制值
【发布时间】:2014-01-02 20:48:10
【问题描述】:

我需要检查 DataGridView 中特定单元格中的值是否输入正确?

在 CellFormating 事件中我有:

if (e.ColumnIndex == 4)
{
    string deger = (string)e.Value;
    deger = String.Format("{0:0.00}", deger);
}

DefaultCellStyle 的格式如下:

dgLog.Columns[4].DefaultCellStyle.Format = "n2";

但这仍然允许用户输入他想要的任何内容。如何处理单元格只允许输入带一位小数的数字?

【问题讨论】:

    标签: c# datagridview


    【解决方案1】:

    添加EditingControlShowing 的事件在EditingControlShowing 中,检查当前单元格是否位于所需的列中。在EditingControlShowing 中注册KeyPress 的新事件(如果上述条件为真)。删除之前在EditingControlShowing 中添加的任何KeyPress 事件。在KeyPress事件中,检查key是否不是digit然后取消输入。

    private void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
    {
       e.Control.KeyPress -= new KeyPressEventHandler(Column1_KeyPress);
       if (dataGridView1.CurrentCell.ColumnIndex == 0) //Desired Column
       {
          TextBox tb = e.Control as TextBox;
          if (tb != null)
          {
            tb.KeyPress += new KeyPressEventHandler(Column1_KeyPress);
          }
        }
    }
    
    private void Column1_KeyPress(object sender, KeyPressEventArgs e)
    {
       if (!char.IsControl(e.KeyChar)
           && !char.IsDigit(e.KeyChar))
        {
            e.Handled = true;
        }
    }
    

    【讨论】:

      【解决方案2】:

      您通常可以使用 DataGridView CellValidating 事件来执行数据验证。请参阅MSDN-1MSDN-2

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2023-03-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-08-02
        • 2018-06-27
        相关资源
        最近更新 更多