Freigeben über


Restricting numeric entries only in a DataGridView column

At times we have a requirement where we need to restrict the user to enter only numbers in a column of a DataGridView to achieve this we need to use EditingControlShowing event of DataGridView, this event is new in .Net framework 2.0 and it occurs when a control for editing a cell is showing. Following sample shows a implementation of it:

private void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
if ((int)(((System.Windows.Forms.DataGridView)(sender)).CurrentCell.ColumnIndex) == 1)
{
e.Control.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.TextboxNumeric_KeyPress);

}
}

private void TextboxNumeric_KeyPress(object sender, KeyPressEventArgs e)
{
Boolean nonNumberEntered;

            nonNumberEntered = true;

            if ((e.KeyChar >= 48 && e.KeyChar <= 57) || e.KeyChar == 8)
{
nonNumberEntered = false ;
}

            if (nonNumberEntered == true)
{
// Stop the character from being entered into the control since it is non-numerical.
e.Handled = true ;
}
else
{
e.Handled = false;
}

        }

Please note that this only for entering positive integers, you may want to look at alternatives to accomodate pasting numericals, non-numeric characters.

Comments

  • Anonymous
    April 23, 2012
    Hi Ketaanh Shah, Thank you a lot for the solution. You really save a lot of time for me to research about this and doing this newly.

  • Anonymous
    December 07, 2012
    The solution has two issues. The first is that once the Keypress event is replace in column one, it is in effect for all columns. The second is that it chains to itself, so that every time a key is pressed in column one the handler gets added again. so every keypress event happens multiple times.