Share via


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

更新:2007 年 11 月

處理來自基礎資料存放區的錯誤是資料輸入應用程式的必要功能。Windows Form DataGridView 控制項透過公開 DataError 事件 (它會在資料存放區偵測到違反條件約束或壞的商務規則時引發),使這項功能更加容易。

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

若要將此主題中的程式碼複製為一份清單,請參閱 HOW TO:處理 Windows Form DataGridView 控制項中的資料輸入期間所發生的錯誤

必要條件

若要完成這個逐步解說,您必須要有:

  • 具有 Northwind SQL Server 範例資料庫之伺服器的存取權。

建立表單

若要處理 DataGridView 控制項中的資料輸入錯誤

  1. 建立一個由 Form 所衍生,而且包含一個 DataGridView 控制項和一個 BindingSource 元件的類別。

    下列的程式碼範例提供基本的初始化,而且包含了一個 Main 方法。

    Imports System
    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()> _
        Shared Sub Main()
            Application.EnableVisualStyles()
            Application.Run(New Form1())
        End Sub
    
    End Class
    
    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);
        }
    
    
    ...
    
    
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.Run(new Form1());
        }
    
    }
    
  2. 在表單的類別定義中實作一個方法,來處理與資料庫連接的細節。

    這個程式碼範使用一個 GetData 方法,此方法會傳回填入 DataTable 物件。請確認您已將 connectionString 變數設定為適合此資料庫的值。

    安全性注意事項:

    在連接字串內儲存機密資訊 (例如密碼) 會影響應用程式的安全性。使用 Windows 驗證 (也稱為整合式安全性) 是控制資料庫存取的更安全方式。如需詳細資訊,請參閱保護連接資訊 (ADO.NET)

    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
    
    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;
    }
    
  3. 實作表單的 Load 事件的處理常式,此事件會初始化 DataGridViewBindingSource,並設定資料繫結。

    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
    
    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);
    }
    
  4. 處理 DataGridView 上的 DataError 事件。

    如果錯誤的內容是一項認可作業,請在 MessageBox 中顯示錯誤。

    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
    
    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.");
        }
    }
    

測試應用程式

您現在可以測試表單以確定它的行為表現如預期般。

若要測試表單

  • 請按 F5 以執行應用程式。

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

後續步驟

這個應用程式提供對 DataGridView 控制項能力的基本認識。您可以用許多方式來自訂 DataGridView 控制項的外觀和行為:

請參閱

工作

HOW TO:處理 Windows Form DataGridView 控制項中的資料輸入期間所發生的錯誤

逐步解說:驗證 Windows Form DataGridView 控制項中的資料

概念

保護連接資訊 (ADO.NET)

參考

DataGridView

BindingSource

其他資源

Windows Form DataGridView 控制項中的資料輸入