I add a few columns to Datagridview dynamically: a dropdownlist and a few textboxes. I would like to make one of textboxes-columns to accept digits only.
DataGridViewComboBoxColumn cbc = new DataGridViewComboBoxColumn();
cbc.DataPropertyName = "Name1";
//I populate combo here
dataGrid.Columns.Add(cbc);
DataGridViewTextBoxColumn column = new DataGridViewTextBoxColumn();
//set column's DataPropertyName, HeaderText, Name
dataGrid.Columns.Add(column);
column = new DataGridViewTextBoxColumn();
//set column's DataPropertyName, HeaderText, Name
dataGrid.Columns.Add(column);
dataGrid.EditingControlShowing +=
new DataGridViewEditingControlShowingEventHandler(dataGrid _EditingControlShowing);
………………………
void dataGrid _EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
DataGridView dgr = (DataGridView)sender;
if (dgr.CurrentCell.ColumnIndex == 2)
{
if (e.Control is TextBox)
{
TextBox tb = e.Control as TextBox;
tb.KeyPress += new KeyPressEventHandler(tb_KeyPress);
}
}
}
void tb_KeyPress(object sender, KeyPressEventArgs e)
{
if (!(char.IsDigit(e.KeyChar)))
{
if (e.KeyChar != '\b' && e.KeyChar != '.') //allow the backspace key and decimal point
{
e.Handled = true;
}
}
}
All goes fine until I start editing a cell of the column 2.
Obviously if (dgr.CurrentCell.ColumnIndex == 2)
doesn’t make much sense - I guess the function iterates all textbox columns and makes them all to accept digits only.
But when I click on dropdown, it somehow refreshes the grid and I can type just anything in column 1 again…until next dataGrid.EditingControlShowing
Any idea how to fix that?
Thanks
ElmarPosted May 25, 2008, 4:41 PM
I'm not sure what IsMatch method has to do with my problem. Perhaps I couldn't explain it clear...All I said is that the following piece of code makes ALL textboxes in the grid to accept digits only when a user tries to edit column 2
if (dgr.CurrentCell.ColumnIndex == 2)
{
if (e.Control is TextBox)
{
TextBox tb = e.Control as TextBox;
tb.KeyPress += new KeyPressEventHandler(tb_KeyPress);
}
}
Bechir BejaouiPosted May 25, 2008, 3:37 AM
foreach(datagridviewtextboxcell c in datagridviewtextboxcolumn)
{
// to do implment somethig with regex class here
}