Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I validate DataGridView input?

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?

like image 730
Masoud Keshavarz Avatar asked Jan 27 '26 19:01

Masoud Keshavarz


1 Answers

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.

like image 96
Ashkan Avatar answered Jan 30 '26 09:01

Ashkan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!