Elmar

Elmar

  • NA
  • 11
  • 0

Datagridview textbox column - digits only

May 24 2008 7:18 PM

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

 


Answers (2)