向用户显示数据输入功能时,通常需要验证输入到表单中的数据。 在将数据提交到数据存储之前,该 DataGridView 类提供了一种执行验证的便捷方法。 可以通过处理 CellValidating 事件来验证数据,该事件由 DataGridView 在当前单元格更改时引发。
在本演练中,你将从 Northwind 示例数据库中的 Customers
表中检索行,并将其显示在 DataGridView 控件中。 当用户编辑列中的单元格并尝试离开单元格 CompanyName
时, CellValidating 事件处理程序将检查新的公司名称字符串以确保它不为空;如果新值是空字符串, DataGridView 将阻止用户的光标离开单元格,直到输入非空字符串。
若要将本主题中的代码复制为单个列表,请参阅 “如何:验证 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); this.Text = "DataGridView validation demo (disallows empty CompanyName)"; }
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) Me.Text = "DataGridView validation demo (disallows empty CompanyName)" 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
在表单的类定义中实现方法,以处理连接到数据库的详细信息。
此代码示例使用一个
GetData
方法,该方法返回一个已填充的 DataTable 对象。 请确保将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. SqlDataAdapter adapter = new SqlDataAdapter(selectCommand, connectionString); DataTable data = new DataTable(); data.Locale = System.Globalization.CultureInfo.InvariantCulture; adapter.Fill(data); 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. Dim adapter As New SqlDataAdapter(selectCommand, connectionString) Dim data As New DataTable() data.Locale = System.Globalization.CultureInfo.InvariantCulture adapter.Fill(data) Return data End Function
为表单的 Load 事件实现一个处理程序,该程序初始化 DataGridView 和 BindingSource,并设置数据绑定。
private void Form1_Load(System.Object sender, System.EventArgs e) { // Attach DataGridView events to the corresponding event handlers. this.dataGridView1.CellValidating += new DataGridViewCellValidatingEventHandler(dataGridView1_CellValidating); this.dataGridView1.CellEndEdit += new DataGridViewCellEventHandler(dataGridView1_CellEndEdit); // 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 控件 CellValidating 和 CellEndEdit 事件的处理程序。
在CellValidating事件处理程序中,您确定
CompanyName
列的单元格值是否为空。 如果单元格值验证失败,请将CancelSystem.Windows.Forms.DataGridViewCellValidatingEventArgs类的属性设置为true
。 这会导致 DataGridView 控件阻止光标离开单元格。 将 ErrorText 行上的属性设置为解释性字符串。 此时会显示包含错误文本的工具提示的错误图标。 在 CellEndEdit 事件处理程序中,将 ErrorText 行上的属性设置为空字符串。 只有当单元格退出编辑模式时,才会发生 CellEndEdit 事件,而如果单元格未通过验证,则无法退出编辑模式。private void dataGridView1_CellValidating(object sender, DataGridViewCellValidatingEventArgs e) { string headerText = dataGridView1.Columns[e.ColumnIndex].HeaderText; // Abort validation if cell is not in the CompanyName column. if (!headerText.Equals("CompanyName")) return; // Confirm that the cell is not empty. if (string.IsNullOrEmpty(e.FormattedValue.ToString())) { dataGridView1.Rows[e.RowIndex].ErrorText = "Company Name must not be empty"; e.Cancel = true; } } void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e) { // Clear the row error in case the user presses ESC. dataGridView1.Rows[e.RowIndex].ErrorText = String.Empty; }
Private Sub dataGridView1_CellValidating(ByVal sender As Object, _ ByVal e As DataGridViewCellValidatingEventArgs) _ Handles dataGridView1.CellValidating Dim headerText As String = _ dataGridView1.Columns(e.ColumnIndex).HeaderText ' Abort validation if cell is not in the CompanyName column. If Not headerText.Equals("CompanyName") Then Return ' Confirm that the cell is not empty. If (String.IsNullOrEmpty(e.FormattedValue.ToString())) Then dataGridView1.Rows(e.RowIndex).ErrorText = _ "Company Name must not be empty" e.Cancel = True End If End Sub Private Sub dataGridView1_CellEndEdit(ByVal sender As Object, _ ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) _ Handles dataGridView1.CellEndEdit ' Clear the row error in case the user presses ESC. dataGridView1.Rows(e.RowIndex).ErrorText = String.Empty End Sub
测试应用程序
现在,你可以测试表单,以确保其行为符合预期。
测试窗体
编译并运行应用程序。
你将看到一个 DataGridView,它里面填充了来自
Customers
表的数据。 双击列中的CompanyName
单元格时,可以编辑该值。 如果删除所有字符并按 TAB 键退出单元格,则 DataGridView 阻止退出。 在单元格中键入非空字符串时,控件 DataGridView 允许退出单元格。
后续步骤
此应用程序可让你基本了解 DataGridView 控件的功能。 可以通过多种方式自定义 DataGridView 控件的外观和行为:
更改边框和标题样式。 有关详细信息,请参阅 如何:更改 Windows 窗体 DataGridView 控件中的边框和网格线样式。
启用或限制用户输入到 DataGridView 控件。 有关详细信息,请参阅如何:防止在 Windows 窗体 DataGridView 控件中添加和删除行和如何:将 Windows 窗体 DataGridView 控件中的列设为只读。
检查用户输入是否存在与数据库相关的错误。 有关详细信息,请参阅 演练:在 Windows 窗体 DataGridView 控件中处理数据输入期间发生的错误。
使用虚拟模式处理非常大的数据集。 有关详细信息,请参阅演练:在 Windows 窗体 DataGridView 控件中实现虚拟模式。
自定义单元格的外观。 有关详细信息,请参阅如何:自定义 Windows 窗体 DataGridView 控件中单元格的外观以及如何:在 Windows 窗体 DataGridView 控件中设置字体和颜色样式。