Wednesday, September 4, 2013

How to validate DataGridView column to allow only numbers in c#

I'll use a windows application form to demonstrate this. Let say you have a datagridview which has to prevent entering Non -numerical values in the particular columns. I'm using Cost and SellingPrice Columns to demonstrate the validation. (Do Not worry about attached image dataset. Just follow the code snippet on validation )

You have to use CellValidating event to tackle this.


Follow the below code snippet for the validation;
private void dataGridViewDistribution_CellValidating(object sender, 
DataGridViewCellValidatingEventArgs e)
{
    DataGridViewColumn col = dataGridViewDistribution.Columns[e.ColumnIndex] as DataGridViewColumn;

    if (col.Name.ToLower() == "cost" || col.Name.ToLower() == "sellingprice")
    {
        DataGridViewTextBoxCell cell = dataGridViewDistribution[e.ColumnIndex, e.RowIndex] as DataGridViewTextBoxCell;
        if (cell != null)
        {
            char[] chars = e.FormattedValue.ToString().ToCharArray();
            foreach (char c in chars)
            {
                if (char.IsDigit(c) == false)
                {
                    MessageBox.Show("You have to enter digits only");
                    e.Cancel = true;
                    break;
                }
            }
        }
    }
}

No comments:

Post a Comment