Make a specific column only accept numeric value in datagridview in Keypress event

Eplzong picture Eplzong · Sep 28, 2012 · Viewed 90.5k times · Source

I need to make datagridview that only accept the numeric value for specific column only in keypress event. Is there any best way to do this?

Answer

Muhammad Mobeen Qureshi picture Muhammad Mobeen Qureshi · Feb 1, 2013
  • 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.

Example:

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;
    }
}