Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validations for Datagridview cell values in C#

I have a windows form application which contains a datgridview. I need to enforce cell validations on the datagridview cells so that it does not accept negative values. I found a suitable code for it from the msdn library.

private void dataGridView1_CellValidating(object sender,
DataGridViewCellValidatingEventArgs e)
{
dataGridView1.Rows[e.RowIndex].ErrorText = "";
int newInteger;

// Don't try to validate the 'new row' until finished  
// editing since there 
// is not any point in validating its initial value. 
if (dataGridView1.Rows[e.RowIndex].IsNewRow) { return; }
if (!int.TryParse(e.FormattedValue.ToString(),
    out newInteger) || newInteger < 0)
{
    e.Cancel = true;
    dataGridView1.Rows[e.RowIndex].ErrorText = "the value must be a Positive integer";
}
}

Unfortunately the code only allows integers to be entered in the datagridview. Since i have a column name as "Item Name" which is supposed to be entered as text there is an issue in the code. It generates an error message when i type in the name of the item.The rest of the cell validations are perfectly working! How am i supposed to edit the code so that it does not generate this error?

Thanks in advance

Mirfath

like image 675
Mirfath Muksith Hafeel Avatar asked Jan 05 '13 14:01

Mirfath Muksith Hafeel


1 Answers

DataGridViewCellValidatingEventArgs e has a .ColumnIndex property which you can check to make sure validation is only done on the column you wish.

private void dataGridView1_CellValidating(object sender,
DataGridViewCellValidatingEventArgs e) {
    if (e.ColumnIndex == dataGridView1.Columns["MyNumericColumnName"].Index) {
        dataGridView1.Rows[e.RowIndex].ErrorText = "";
        int newInteger;

        // Don't try to validate the 'new row' until finished  
        // editing since there 
        // is not any point in validating its initial value. 
        if (dataGridView1.Rows[e.RowIndex].IsNewRow) { return; }
        if (!int.TryParse(e.FormattedValue.ToString(),
            out newInteger) || newInteger < 0)
        {
            e.Cancel = true;
            dataGridView1.Rows[e.RowIndex].ErrorText = "the value must be a Positive integer";
        }
    }
}
like image 110
C-Pound Guru Avatar answered Oct 03 '22 23:10

C-Pound Guru