演练:处理在 Windows 窗体 DataGridView 控件中输入数据时发生的错误
处理基础数据存储中的错误是数据输入应用程序的必需功能。 Windows 窗体 DataGridView 控件通过公开 DataError 事件(在数据存储检测到约束冲突或违反业务规则时引发)来轻松实现此目的。
在本演练中,将从 Northwind 示例数据库的 Customers
表中检索行并将它们显示在 DataGridView 控件中。 当在新行或已编辑的现有行中检测到重复的 CustomerID
值时,将发生 DataError 事件,并将通过显示描述异常的 MessageBox 来处理该事件。
若要将本主题中的代码复制为单个列表,请参阅如何:处理在 Windows 窗体 DataGridView 控件中输入数据时发生的错误。
先决条件
若要完成本演练,你将需要:
- 可访问具有 Northwind SQL Server 示例数据库的服务器。
创建窗体
处理 DataGridView 控件中的数据输入错误
创建一个派生自 Form 并包含 DataGridView 控件和 BindingSource 组件的类。
以下代码示例提供基本初始化并包含一个
Main
方法。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); }
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] static void Main() { Application.EnableVisualStyles(); Application.Run(new Form1()); } }
<STAThread()> _ Shared Sub Main() Application.EnableVisualStyles() Application.Run(New Form1()) End Sub End Class
在窗体的类定义中实现一个方法,用于处理连接到数据库的详细信息。
此代码示例使用返回填充的 DataTable 对象的
GetData
方法。 请确保将connectionString
变量设置为适合数据库的值。重要
将敏感信息(如密码)存储在连接字符串中可能会影响应用程序的安全性。 若要控制对数据库的访问,一种较为安全的方法是使用 Windows 身份验证(也称为集成安全性)。 有关详细信息,请参阅保护连接信息。
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; }
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
为窗体的 Load 事件实现一个处理程序,用于初始化 DataGridView 和 BindingSource 并设置数据绑定。
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); }
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
处理 DataGridView 上的 DataError 事件。
如果错误的上下文是提交操作,则在 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."); } }
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
测试应用程序
现在可以测试窗体,以确保它的行为符合预期。
测试窗体
按 F5 运行该应用程序。
你将看到一个 DataGridView 控件,其中填充了 Customers 表中的数据。 如果为
CustomerID
输入重复值并提交编辑,则单元格值将自动还原,你将看到显示数据输入错误的 MessageBox。
后续步骤
此应用程序让你对 DataGridView 控件的功能有了一个基本的了解。 可以通过多种方式自定义 DataGridView 控件的外观和行为:
更改边框和标题样式。 有关详细信息,请参阅如何:更改 Windows 窗体 DataGridView 控件中的边框和网格线样式。
启用或限制对 DataGridView 控件的用户输入。 有关详细信息,请参阅如何:防止在 Windows 窗体 DataGridView 控件中添加和删除行和如何:将 Windows 窗体 DataGridView 控件中的列设为只读。
验证对 DataGridView 控件的用户输入。 有关详细信息,请参阅演练:验证 Windows 窗体 DataGridView 控件中的数据。
使用虚拟模式处理海量数据集。 有关详细信息,请参阅演练:在 Windows 窗体 DataGridView 控件中实现虚拟模式。
自定义单元格的外观。 有关详细信息,请参阅如何:自定义 Windows 窗体 DataGridView 控件中单元格的外观和如何:设置 Windows 窗体 DataGridView 控件的默认单元格样式。
另请参阅
反馈
https://aka.ms/ContentUserFeedback。
即将发布:在整个 2024 年,我们将逐步淘汰作为内容反馈机制的“GitHub 问题”,并将其取代为新的反馈系统。 有关详细信息,请参阅:提交和查看相关反馈