Export (0) Print
Expand All

How to: Handle Errors That Occur During Data Entry in the Windows Forms DataGridView Control

The following code example demonstrates how to use the DataGridView control to report data entry errors to the user.

For a complete explanation of this code example, see Walkthrough: Handling Errors that Occur During Data Entry in the Windows Forms DataGridView Control.


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);

    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;

    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.");

    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;

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


Compiling the Code


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 Securing Connection Strings.

See Also

Community Additions

© 2014 Microsoft