Hi, how i prevent the user from entering data other than numbers to a DataGridView cell ?
Printable View
Hi, how i prevent the user from entering data other than numbers to a DataGridView cell ?
If you bind the datagridview to a collection of custom objects, the cells will be validated as the object's property types.
For instance, if you have a datagridview which is bound to a generic list of Person objects. This class could have an integer property defined - let's call it Age. When editing a cell, the input will not be accepted as anything other than an int.
Note, however, that committing another type, such as a string, will cause the datagridview's DataError event to be raised.
Hope it helps :)
thanks foamy, i found this solution :
Code:...
this.dataGridView1.EditingControlShowing += new System.Windows.Forms.DataGridViewEditingControlShowingEventHandler(this.DataGridView1EditingControlShowing);
...
void DataGridView1EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
if(e.Control is TextBox)
{
TextBox tb = e.Control as TextBox;
tb.KeyPress -= new KeyPressEventHandler(tb_KeyPress);
if (this.dataGridView1.CurrentCell.ColumnIndex != 0)
{
tb.KeyPress += new KeyPressEventHandler(tb_KeyPress);
}
}
}
void tb_KeyPress(object sender, KeyPressEventArgs e)
{
if (!(char.IsDigit(e.KeyChar)))
{
e.Handled = true;
}
}