I need to check if value in specific cell in DataGridView is correctly entered?
In CellFormating event I have:
if (e.ColumnIndex == 4)
{
string deger = (string)e.Value;
deger = String.Format("{0:0.00}", deger);
}
And DefaultCellStyle is formated like:
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. Register a new event of KeyPress
in EditingControlShowing
(if above condition is true).Remove any KeyPress
event added previously in EditingControlShowing
. In KeyPress
event, check that if key
is not digit
then cancel the input.
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;
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.