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