简体   繁体   English

检查DataGridView Cell中的十进制值

[英]Check decimal value in DataGridView Cell

I need to check if value in specific cell in DataGridView is correctly entered? 我需要检查DataGridView中特定单元格中的值是否正确输入?

In CellFormating event I have: 在CellFormating活动中,我有:

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

And DefaultCellStyle is formated like: 而DefaultCellStyle的格式如下:

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

But this still allows user to enter whatever he want. 但这仍然允许用户输入他想要的任何东西。 How to handle cell to allow entering only numbers with one decimal point? 如何处理单元格以允许只输入一个小数点的数字?

Add an event of EditingControlShowing In EditingControlShowing , check that if the current cell lies in the desired column. 添加EditingControlShowing事件在EditingControlShowing ,检查当前单元格是否位于所需列中。 Register a new event of KeyPress in EditingControlShowing (if above condition is true).Remove any KeyPress event added previously in EditingControlShowing . EditingControlShowing注册KeyPress的新事件(如果满足以上条件)。 EditingControlShowing先前在EditingControlShowing添加的任何KeyPress事件。 In KeyPress event, check that if key is not digit then cancel the input. 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;
    }
}

You could use the DataGridView CellValidating event to perform data validation in general. 您可以使用DataGridView CellValidating事件来执行一般的数据验证。 See MSDN-1 and MSDN-2 . 请参阅MSDN-1MSDN-2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM