繁体   English   中英

检查DataGridView Cell中的十进制值

[英]Check decimal value in DataGridView Cell

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

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

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

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

暂无
暂无

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

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