共用方式為


逐步解說:處理 Windows Form DataGridView 控制項中的資料輸入期間所發生的錯誤

處理基礎資料存放區的錯誤是資料輸入應用程式的必要功能。 Windows Forms DataGridView 控制項公開 DataError 事件,讓此作業變得簡單,而在資料存放區偵測到條件約束違規或商務規則中斷時,會引發此事件。

在本逐步解說中,您將從 Northwind 範例資料庫中的 Customers 資料表擷取資料列,並將其顯示在 DataGridView 控制項中。 在新的資料列或已編輯的現有資料列中偵測到重複的 CustomerID 值時,將會發生 DataError 事件,而顯示可描述例外狀況的 MessageBox 即可處理此事件。

若要將本主題中的程式碼複製為單一清單,請參閱如何:處理 Windows Forms 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. 在表單的類別定義中實作方法,以處理連線到資料庫的詳細資料。

    此程式碼範例會使用傳回填入 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
    
  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. 處理 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 執行應用程式。

    您將會看到已填寫 Customers 資料表資料的 DataGridView 控制項。 如果您輸入重複的 CustomerID 值,並認可編輯,則將會自動還原儲存格值,而且您將會看到可顯示資料輸入錯誤的 MessageBox

後續步驟

此應用程式可讓您對 DataGridView 控制項的功能有基本了解。 您可以透過數種方式自訂 DataGridView 控制項的外觀和行為:

另請參閱