更新:2007 年 11 月
处理基础数据存储区中的错误是数据输入应用程序所必备的功能。Windows 窗体 DataGridView 控件通过公开 DataError 事件来轻松实现此类错误的处理;当数据存储区检测到约束冲突或违反业务规则时将引发该事件。
在本演练中,将从 Northwind 示例数据库的 Customers 表中检索行,并将检索到的行显示在 DataGridView 控件中。当在新行或编辑的现有行中检测到重复的 CustomerID 值时,将发生 DataError 事件,并通过显示一个描述该异常的 MessageBox 对此事件进行处理。
若要以单个列表的形式复制本主题中的代码,请参见 如何:处理在 Windows 窗体 DataGridView 控件中输入数据时发生的错误。
先决条件
若要完成本演练,您需要:
- 对 Northwind SQL Server 示例数据库所在的服务器的访问权限。
创建窗体
在 DataGridView 控件中处理数据输入错误
- 创建一个从 Form 派生的类,该类包含一个 DataGridView 控件和一个 BindingSource 组件。 - 下面的代码示例提供了基本的初始化功能,并包含一个 Main 方法。 - Imports System Imports System.Data Imports System.Data.SqlClient Imports System.Windows.Forms Public Class Form1 Inherits System.Windows.Forms.Form Private WithEvents dataGridView1 As New DataGridView() Private bindingSource1 As New BindingSource() Public Sub New() ' Initialize the form. Me.dataGridView1.Dock = DockStyle.Fill Me.Controls.Add(dataGridView1) End Sub ... <STAThread()> _ Shared Sub Main() Application.EnableVisualStyles() Application.Run(New Form1()) End Sub End Class- 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()); } }
- 在窗体的类定义中实现一个方法,用于处理有关与数据库的连接的详细信息。 - 此代码示例使用 GetData 方法,该方法返回填充的 DataTable 对象。请确保将 connectionString 变量设置为适用于您的数据库的值。 .gif) 安全说明: 安全说明:- 将敏感信息(如密码)存储在连接字符串中可能会影响应用程序的安全性。若要控制对数据库的访问,一种较为安全的方法是使用 Windows 身份验证(也称为集成安全性)。有关更多信息,请参见保护连接信息 (ADO.NET)。 - Private Shared Function GetData(ByVal selectCommand As String) As DataTable Dim connectionString As String = _ "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. Dim adapter As New SqlDataAdapter(selectCommand, connectionString) Dim data As New DataTable() data.Locale = System.Globalization.CultureInfo.InvariantCulture adapter.Fill(data) adapter.FillSchema(data, SchemaType.Source) Return data End Function- 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; }
- 为窗体的 Load 事件实现一个处理程序,该事件初始化 DataGridView 和 BindingSource 并设置数据绑定。 - Private Sub Form1_Load(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Me.Load ' Initialize the BindingSource and bind the DataGridView to it. bindingSource1.DataSource = GetData("select * from Customers") Me.dataGridView1.DataSource = bindingSource1 Me.dataGridView1.AutoResizeColumns( _ DataGridViewAutoSizeColumnsMode.AllCellsExceptHeader) End Sub- 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); }
- 在 DataGridView 中处理 DataError 事件。 - 如果错误发生在提交操作过程中,则在 MessageBox 中显示该错误。 - Private Sub dataGridView1_DataError(ByVal sender As Object, _ ByVal e As DataGridViewDataErrorEventArgs) _ Handles dataGridView1.DataError ' If the data source raises an exception when a cell value is ' commited, display an error message. If e.Exception IsNot Nothing AndAlso _ e.Context = DataGridViewDataErrorContexts.Commit Then MessageBox.Show("CustomerID value must be unique.") End If End Sub- 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."); } }
测试应用程序
现在可以测试窗体,以确保它的行为与预期相同。
测试窗体
- 按 F5 运行应用程序。 - 您将看到一个用 Customers 表中的数据填充的 DataGridView 控件。如果为 CustomerID 输入重复的值并提交编辑结果,则该单元格的值将自动恢复为原来的值,您将看到一个显示数据输入错误的 MessageBox。 
后续步骤
此应用程序使您对 DataGridView 控件的功能有一个基本了解。您可以通过以下几种方法来自定义 DataGridView 控件的外观和行为:
- 更改边框和标题样式。有关更多信息,请参见 如何:更改 Windows 窗体 DataGridView 控件中的边框和网格线的样式。 
- 允许或限制用户向 DataGridView 控件中输入数据。有关更多信息,请参见如何:防止在 Windows 窗体 DataGridView 控件中添加和删除行和如何:使 Windows 窗体 DataGridView 控件中的列只读。 
- 对用户在 DataGridView 控件中输入的数据进行验证。有关更多信息,请参见 演练:验证 Windows 窗体 DataGridView 控件中的数据。 
- 使用虚拟模式处理特大数据集。有关更多信息,请参见 演练:在 Windows 窗体 DataGridView 控件中实现虚拟模式。 
- 自定义单元格的外观。有关更多信息,请参见 如何:自定义 Windows 窗体 DataGridView 控件中单元格的外观 和 如何:设置 Windows 窗体 DataGridView 控件的默认单元格样式。 
请参见
任务
如何:处理在 Windows 窗体 DataGridView 控件中输入数据时发生的错误
演练:验证 Windows 窗体 DataGridView 控件中的数据