Friday, March 15, 2013

How to Validate/Restrict DataGridView for Entering Only Number or Characters (if required)


1. Number Only Textbox with backspace
For that we can use EditingControlShowing Event of the datagridview



 Double click the EditingControlShowing event of the DataGridView

//Now we can create user defined event named as DataGrid_KeyPress
private void DataGrid_KeyPress(object sender, KeyPressEventArgs e)
{
    if ((e.KeyChar != (char)Keys.Back) && !char.IsDigit(e.KeyChar))
    {
        e.Handled = true;
    }   
}

//This code is to validate all columns
private void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
   e.Control.KeyPress -= new KeyPressEventHandler(DataGrid_KeyPress);
   TextBox tb = e.Control as TextBox;
   if (tb != null)
   {
       tb.KeyPress += new KeyPressEventHandler(DataGrid_KeyPress);
   }
}

//This code is to validate particular columns
private void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
     e.Control.KeyPress -= new KeyPressEventHandler(DataGrid_KeyPress);
     //Check columns whatever you required
     if (dataGridView1.CurrentCell.ColumnIndex == 2)
     {
         TextBox tb = e.Control as TextBox;
         if (tb != null)
         {
              tb.KeyPress += new KeyPressEventHandler(DataGrid_KeyPress);
         }
     }
     if (dataGridView1.CurrentCell.ColumnIndex == 3)
     {
         TextBox tb = e.Control as TextBox;
         if (tb != null)
         {
              tb.KeyPress += new KeyPressEventHandler(DataGrid_KeyPress);
         }
     }
}

2. Number Only Textbox with backspace and only one dot    
Then change the above code with this, balance all same

private void DataGrid_KeyPress(object sender, KeyPressEventArgs e)
{
    if ((e.KeyChar != (char)Keys.Back) && !char.IsDigit(e.KeyChar) && e.KeyChar != '.')
     {
        e.Handled = true;
     }
     //Here is the code that will allow one decimal point
     if (e.KeyChar == '.' && (sender as TextBox).Text.IndexOf('.') > -1)
     {
        e.Handled = true;
     }
}

3. If we want to add only one character and other number only means we can replace ‘.’(dot/point) with the special characters like A~Z or a~z or  ,;[]' " \ etc
Then change the above code with this, balance all same

private void DataGrid_KeyPress(object sender, KeyPressEventArgs e)
{
    if ((e.KeyChar != (char)Keys.Back) && !char.IsDigit(e.KeyChar) && e.KeyChar != 'c')
     {
        e.Handled = true;
     }
     //Here is the code that will allow one decimal point
     if (e.KeyChar == 'c' && (sender as TextBox).Text.IndexOf('c') > -1)
     {
        e.Handled = true;
     }
}

4 comments:

Comment Here..