Walkthrough: Handling Errors that Occur During Data Entry in the Windows Forms DataGridView Control


Handling errors from the underlying data store is a required feature for a data-entry application. The Windows Forms DataGridView control makes this easy by exposing the DataError event, which is raised when the data store detects a constraint violation or a broken business rule.

In this walkthrough, you will retrieve rows from the Customers table in the Northwind sample database and display them in a DataGridView control. When a duplicate CustomerID value is detected in a new row or an edited existing row, the DataError event will occur, which will be handled by displaying a MessageBox that describes the exception.

To copy the code in this topic as a single listing, see How to: Handle Errors That Occur During Data Entry in the Windows Forms DataGridView Control.

In order to complete this walkthrough, you will need:

  • Access to a server that has the Northwind SQL Server sample database.

To handle data-entry errors in the DataGridView control

  1. Create a class that derives from Form and contains a DataGridView control and a BindingSource component.

    The following code example provides basic initialization and includes a Main method.

    using System;
    using System.Data;
    using System.Data.SqlClient;
    using System.Windows.Forms;
    public class Form1 : System.Windows.Forms.Form
        private DataGridView dataGridView1 = new DataGridView();
        private BindingSource bindingSource1 = new BindingSource();
        public Form1()
            // Initialize the form.
            this.dataGridView1.Dock = DockStyle.Fill;
            this.Load += new EventHandler(Form1_Load);

        static void Main()
            Application.Run(new Form1());

  2. Implement a method in your form's class definition for handling the details of connecting to the database.

    This code example uses a GetData method that returns a populated DataTable object. Be sure that you set the connectionString variable to a value that is appropriate for your database.

    System_CAPS_ICON_important.jpg Important

    Storing sensitive information, such as a password, within the connection string can affect the security of your application. Using Windows Authentication (also known as integrated security) is a more secure way to control access to a database. For more information, see Protecting Connection Information.

        private static DataTable GetData(string selectCommand)
            string connectionString =
                "Integrated Security=SSPI;Persist Security Info=False;" +
                "Initial Catalog=Northwind;Data Source=localhost;Packet Size=4096";
            // Connect to the database and fill a data table, including the 
            // schema information that contains the CustomerID column 
            // constraint.
            SqlDataAdapter adapter =
                new SqlDataAdapter(selectCommand, connectionString);
            DataTable data = new DataTable();
            data.Locale = System.Globalization.CultureInfo.InvariantCulture;
            adapter.FillSchema(data, SchemaType.Source);
            return data;

  3. Implement a handler for your form's Load event that initializes the DataGridView and BindingSource and sets up the data binding.

        private void Form1_Load(System.Object sender, System.EventArgs e)
            // Attach the DataError event to the corresponding event handler.
            this.dataGridView1.DataError +=
                new DataGridViewDataErrorEventHandler(dataGridView1_DataError);
            // Initialize the BindingSource and bind the DataGridView to it.
            bindingSource1.DataSource = GetData("select * from Customers");
            this.dataGridView1.DataSource = bindingSource1;

  4. Handle the DataError event on the DataGridView.

    If the context for the error is a commit operation, display the error in a MessageBox.

        private void dataGridView1_DataError(object sender,
            DataGridViewDataErrorEventArgs e)
            // If the data source raises an exception when a cell value is 
            // commited, display an error message.
            if (e.Exception != null &&
                e.Context == DataGridViewDataErrorContexts.Commit)
                MessageBox.Show("CustomerID value must be unique.");

You can now test the form to make sure it behaves as expected.

To test the form

  • Press F5 to run the application.

    You will see a DataGridView control filled with data from the Customers table. If you enter a duplicate value for CustomerID and commit the edit, the cell value will revert automatically and you will see a MessageBox that displays the data entry error.

This application gives you a basic understanding of the DataGridView control's capabilities. You can customize the appearance and behavior of the DataGridView control in several ways:

Data Entry in the Windows Forms DataGridView Control
How to: Handle Errors That Occur During Data Entry in the Windows Forms DataGridView Control
Walkthrough: Validating Data in the Windows Forms DataGridView Control
Protecting Connection Information