How can I validate DataGridView input?

c# data-binding datagridview entity-framework sql-server

Question

I have some serious problem with DataGridView input validation:

I'm working on a project with Entity Framework and I've bound a DataGridView element to a database.

If the user inserts some data into a non-nullable column, and after that clears the data to leave the column blank, then clicks on another DataGridView cell, an exception occurs and I get a run-time error.

Alternately, if a user tries to insert a string into an integer column, they get a very long error message which isn't user friendly at all.

Is it any easy way to validate DataGridView cells?

1
2
9/19/2013 11:33:40 AM

Popular Answer

I believe you are looking for DataGridView.DataError event. you should handle this event if you want to have custom validation on data. something like this:

    private void Form1_Load(object sender, EventArgs e)
    {
        dataGridView1.DataSource = entities;
        dataGridView1.DataError += new DataGridViewDataErrorEventHandler(dataGridView1_DataError);
    }

    void dataGridView1_DataError(object sender, DataGridViewDataErrorEventArgs e)
    {
        // you can obtain current editing value like this:
        string value = null;
        var ctl = dataGridView1.EditingControl as DataGridViewTextBoxEditingControl;

        if (ctl != null)
            value = ctl.Text;

        // you can obtain the current commited value
        object current = dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value;
        string message;
        switch (e.ColumnIndex)
        {
            case 0:
                // bound to integer field
                message = "the value should be a number";
                break;
            case 1:
                // bound to date time field
                message = "the value should be in date time format yyyy/MM/dd hh:mm:ss";
                break;
            // other columns
            default:
                message = "Invalid data";
                break;
        }

        MessageBox.Show(message);
    }

you can check the value of entered data and show appropriate error message for that value. for example if value is null or empty and the field is not nullable, you can show a message indicating that the value cannot be empty.

Hope this helps.

2
12/20/2013 12:41:25 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow