Skip to content

Datagridview textbox column - digits only

Elmar

Asked May 24, 2008, 3:18 PM EDT2 answers
Share
LinkedInX

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.

 

Java
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);

………………………

 

TypeScript
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

2 Answers

Know the answer? Post it. Somebody with the same question will find it here.

  • Bechir Bejaoui
    0
    try to use regex class and its method IsMatch and apply it to the datagridviewtextboxcolumn

    foreach(datagridviewtextboxcell c in datagridviewtextboxcolumn)
    {
       //    to do implment somethig with regex class here
    }
    0
  • 0

    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

    Code
    if (dgr.CurrentCell.ColumnIndex == 2)
    {
           if (e.Control is TextBox)
          {
                 TextBox tb = e.Control as TextBox;
                 tb.KeyPress += new KeyPressEventHandler(tb_KeyPress);
           }
    }
    0