C# 检查DataGridView单元格中的十进制值

C# 检查DataGridView单元格中的十进制值,c#,datagridview,C#,Datagridview,我需要检查DataGridView中特定单元格中的值是否正确输入 在CellFormatting事件中,我有: if (e.ColumnIndex == 4) { string deger = (string)e.Value; deger = String.Format("{0:0.00}", deger); } DefaultCellStyle的格式如下: dgLog.Columns[4].DefaultCellStyle.Format = "n2"; 但这仍然允许用户输入

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

在CellFormatting事件中,我有:

if (e.ColumnIndex == 4)
{
    string deger = (string)e.Value;
    deger = String.Format("{0:0.00}", deger);
}
DefaultCellStyle的格式如下:

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

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

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

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

通常,您可以使用DataGridView CellValidating事件来执行数据验证。见和