演练:在 Windows 窗体 DataGridView 控件中验证数据

向用户显示数据输入功能时,通常需要验证输入到窗体中的数据。 DataGridView 类提供了一种在将数据提交到数据存储之前执行验证的便捷方法。 可以通过处理 CellValidating 事件来验证数据,该事件在当前单元格更改时由 DataGridView 引发。

在本演练中,将从 Northwind 示例数据库的 Customers 表中检索行并将它们显示在 DataGridView 控件中。 当用户编辑 CompanyName 列中的单元格并尝试离开该单元格时,CellValidating 事件处理程序将检查新的公司名称字符串以确保它不为空;如果新值是空字符串,DataGridView 将阻止用户的光标离开单元格,直到输入非空字符串。

若要将本主题中的代码复制为单个列表,请参阅如何:在 Windows 窗体 DataGridView 控件中验证数据

先决条件

若要完成本演练,你将需要:

  • 可访问具有 Northwind SQL Server 示例数据库的服务器。

创建窗体

验证 DataGridView 中输入的数据

  1. 创建一个派生自 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
    
  2. 在窗体的类定义中实现一个方法,用于处理连接到数据库的详细信息。

    此代码示例使用返回填充的 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.
        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
    
  3. 为窗体的 Load 事件实现一个处理程序,用于初始化 DataGridViewBindingSource 并设置数据绑定。

    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
    
  4. DataGridView 控件的 CellValidatingCellEndEdit 事件实现处理程序。

    CellValidating 事件处理程序用于确定 CompanyName 列中单元格的值是否为空。 如果单元格值验证失败,请将 System.Windows.Forms.DataGridViewCellValidatingEventArgs 类的 Cancel 属性设置为 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
    

测试应用程序

现在可以测试窗体,以确保它的行为符合预期。

测试窗体

  • 编译并运行该应用程序。

    你将看到填充有 Customers 表中数据的 DataGridView。 双击 CompanyName 列中的单元格时,可以编辑该值。 如果删除所有字符并按 TAB 键退出单元格,则 DataGridView 会阻止你退出。 在单元格中键入非空字符串时,控件 DataGridView 允许你退出单元格。

后续步骤

此应用程序让你对 DataGridView 控件的功能有了一个基本的了解。 可以通过多种方式自定义 DataGridView 控件的外观和行为:

另请参阅