检查DataGridView Cell中的十进制值

时间:2014-01-02 12:19:37

标签: c# datagridview

我需要检查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";

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

2 个答案:

答案 0 :(得分:1)

EditingControlShowing中添加EditingControlShowing事件,检查当前单元格是否位于所需列中。在KeyPress中注册EditingControlShowing的新活动(如果符合上述条件)。删除先前在KeyPress中添加的EditingControlShowing个活动。在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;
    }
}

答案 1 :(得分:1)

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