我需要检查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";
但这仍然允许用户输入他想要的任何内容。如何处理单元格以仅允许输入带有一个小数点的数字?
答案 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)