演练:处理在 Windows 窗体 DataGridView 控件中输入数据时发生的错误

处理基础数据存储中的错误是数据输入应用程序所需的功能。 Windows 窗体 DataGridView 控件通过公开 DataError 事件(在数据存储检测到约束冲突或违反业务规则时引发)来轻松实现此目的。

在本演练中,你将从 Northwind 示例数据库中的 Customers 表中检索行,并将其显示在 DataGridView 控件中。 在新行或编辑的现有行中检测到重复 CustomerID 值时,将发生 DataError 事件,这将通过显示描述异常的 MessageBox 进行处理。

若要将本主题中的代码复制为单个列表,请参阅 如何:在 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);
        }
    
    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
    
  2. 在表单的类定义中实现方法,以处理连接到数据库的详细信息。

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

    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
    
  4. 处理 DataError 上的 DataGridView 事件。

    如果错误的上下文是提交操作,则会在 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 控件的外观和行为:

另请参阅