RSS

How to validate DataGridView cell value

06 Mar

Every now and then cell values of DataGridView have to be validated. We could use CellValidating and CellEndEdit events to accomplish this. Here is a simple example to check if user input is empty or incorrect format:

private void MyDataGridView_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
{
    string columnName = this.MyDataGridView.Columns[e.ColumnIndex].Name;

    // Check for the column to validate
    if (columnName.Equals("MyColumn"))
    {
        // Check if the input is empty
        if (string.IsNullOrEmpty(e.FormattedValue.ToString()))
        {
            this.MyDataGridView.Rows[e.RowIndex].ErrorText = "MyColumn could not be empty.";
            e.Cancel = true;
        }
        else
        {
            // Check if the input format is correct
            Regex datePattern = new Regex("((19|20)[0-9]{2}[/](0[1-9]|1[012])[/](0[1-9]|[12][0-9]|3[01]))");
            if (!datePattern.IsMatch(e.FormattedValue.ToString()))
            {
                this.MyDataGridView.Rows[e.RowIndex].ErrorText = "Format incorrect: \"yyyy/MM/dd\"";
                e.Cancel = true;
            }
        }
    }
}

private void MyDataGridView_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
    this.MyDataGridView.Rows[e.RowIndex].ErrorText = string.Empty;
}

See the thorough explanation from Walkthrough: Validating Data in the Windows Forms DataGridView Control.

Advertisements
 
1 Comment

Posted by on March 6, 2012 in .NET, C#

 

One response to “How to validate DataGridView cell value

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: