pavan
pavan

Reputation: 149

how to do validations for numeric,double and empty values for datagridview

how to do validations for numeric,double and empty values for datagridview in c# windows application.Text values should not be allowed to enter the cells which are numeric or double.how to do it?

Upvotes: 1

Views: 3496

Answers (4)

Isaac Broyles
Isaac Broyles

Reputation: 111

If you'd like to restrict anything but numbers from being entered, you need to handle the EditingControlShowing event on the DataGridView. It can be done like this:

dataGridView.EditingControlShowing = new DataGridViewEditingControlShowingEventHandler (dataGridView_EditingControlShowing);

Then, define your handler:

    void dataGridView_EditingControlShowing (object sender, DataGridViewEditingControlShowingEventArgs e)
    {
        TextBox tx = e.Control as TextBox;
        tx.KeyPress += new KeyPressEventHandler (tx_KeyPress_int);
    }

Then, define your KeyPress handler, and only handle numeric characters:

    void tx_KeyPress_int (object sender, KeyPressEventArgs e)
    {
        if (!(char.IsNumber (e.KeyChar) || e.KeyChar == '\b'))
        {
            //is NOT number or is Backspace key
            e.Handled = true;
        }
    }

Adjust to suit your exact needs accordingly (i.e. handle only input on a certain column, etc.)

Upvotes: 1

Glory Raj
Glory Raj

Reputation: 17701

You Can validate datagrid view cell like this...

private void dataGridView1_CellValidating(object sender,DataGridViewCellValidatingEventArgs e)
{
   // Validate the CompanyName entry by disallowing empty strings.
    if (dataGridView1.Columns[e.ColumnIndex].Name == "CompanyName")
    {
        if (e.FormattedValue == null && String.IsNullOrEmpty(e.FormattedValue.ToString()))
        {
          dataGridView1.Rows[e.RowIndex].ErrorText =
            "Company Name must not be empty";
           e.Cancel = true;
        }
   }
}

void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
     // Clear the row error in case the user presses ESC.   
      dataGridView1.Rows[e.RowIndex].ErrorText = String.Empty;
}

This validates only empty values , if you want validate numericals you can do like this... I hope it will helps you...

Upvotes: 1

Frank Myat Thu
Frank Myat Thu

Reputation: 4474

Please read this link.

http://msdn.microsoft.com/en-us/library/aa730881(v=vs.80).aspx

@@Edit ,
if you try to use your own custom numeric control,
1. you no need to check any additional validation.
2. It is reusable.

Upvotes: 0

mao
mao

Reputation: 1404

If you want to validate cell values when user trying to leave cell, you should handle DataGridView.CellValidating event and process cell value there. If you want to validate value when user typing it, you may handle KeyPress event.

To validate numeric values you may use code like this:

int number = 0;
if(!int.TryParce(cell.Value.ToString(), out number))
{ 
    //report about error input 
}

Upvotes: 0

Related Questions