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.
To handle data-entry errors in the DataGridView control
-
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.Controls.Add(dataGridView1); this.Load += new EventHandler(Form1_Load); } ... [STAThread] static void Main() { Application.EnableVisualStyles(); Application.Run(new Form1()); } }
-
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.
Security Note 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.
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.Fill(data); adapter.FillSchema(data, SchemaType.Source); return data; }
-
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; this.dataGridView1.AutoResizeColumns( DataGridViewAutoSizeColumnsMode.AllCellsExceptHeader); }
-
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:
-
Change border and header styles. For more information, see How to: Change the Border and Gridline Styles in the Windows Forms DataGridView Control.
-
Enable or restrict user input to the DataGridView control. For more information, see How to: Prevent Row Addition and Deletion in the Windows Forms DataGridView Control, and How to: Make Columns Read-Only in the Windows Forms DataGridView Control.
-
Validate user input to the DataGridView control. For more information, see Walkthrough: Validating Data in the Windows Forms DataGridView Control.
-
Handle very large data sets using virtual mode. For more information, see Walkthrough: Implementing Virtual Mode in the Windows Forms DataGridView Control.
-
Customize the appearance of cells. For more information, see How to: Customize the Appearance of Cells in the Windows Forms DataGridView Control and How to: Set Default Cell Styles for the Windows Forms DataGridView Control.
Tasks
How to: Handle Errors That Occur During Data Entry in the Windows Forms DataGridView ControlWalkthrough: Validating Data in the Windows Forms DataGridView Control
Reference
DataGridViewBindingSource