Share via


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

更新:2007 年 11 月

當您提供資料輸入功能給使用者時,通常您必須驗證輸入表單中的資料。DataGridView 類別提供了一個方便的方法,可以在資料被認可並寫入資料存放區之前進行驗證。您可以處理 CellValidating 事件來驗證資料,這個事件是在目前的儲存格發生變更時由 DataGridView 所引發。

在這個逐步解說中,您將從 Northwind 範例資料庫的 Customers 資料表擷取資料列,並在 DataGridView 控制項中顯示這些資料列。當使用者編輯了位於 CompanyName 資料行中的儲存格,而且試圖離開該儲存格時,CellValidating 事件處理常式將會檢查新的公司名稱字串以確保其不是空字串;如果新值是一個空字串,DataGridView 會防止使用者的游標離開該儲存格,直到輸入了一個不是非空字串為止。

若要將此主題中的程式碼複製為一份清單,請參閱 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)
            Me.Text = "DataGridView validation demo (disallows empty CompanyName)"
    
        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);
            this.Text = "DataGridView validation demo (disallows empty CompanyName)";
        }
    
    
    ...
    
    
        [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.
        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
    
    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;
    }
    
  3. 為表單中初始化 DataGridViewBindingSourceLoad 事件實作處理常式,並且設定資料繫結。

    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 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);
    }
    
  4. 實作 DataGridView 控制項的 CellValidatingCellEndEdit 事件之處理常式。

    CellValidating 事件處理常式就是您判斷 CompanyName 資料行中的儲存格是否空白的地方。如果儲存格的值驗證失敗,則將 System.Windows.Forms.DataGridViewCellValidatingEventArgs 類別的 Cancel 屬性設定為 true。這會讓 DataGridView 控制項防止游標離開儲存格。在資料列的 ErrorText 屬性中設定一段說明字串。這會顯示一個具有錯誤圖示的工具提示,其中包含了錯誤說明文字。在 CellEndEdit 事件處理常式中,將資料列的 ErrorText 屬性設定至該空字串。只有當儲存格離開編輯模式時,才會發生 CellEndEdit 事件,但是如果儲存格驗證失敗,就無法離開編輯模式。

    Private Sub dataGridView1_CellValidating(ByVal sender As Object, _
        ByVal e As DataGridViewCellValidatingEventArgs) _
        Handles dataGridView1.CellValidating
    
        ' Validate the CompanyName entry by disallowing empty strings.
        If dataGridView1.Columns(e.ColumnIndex).Name = "CompanyName" Then
            If e.FormattedValue IsNot Nothing AndAlso _
                String.IsNullOrEmpty(e.FormattedValue.ToString()) Then
    
                dataGridView1.Rows(e.RowIndex).ErrorText = _
                    "Company Name must not be empty"
                e.Cancel = True
    
            End If
        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
    
    private void dataGridView1_CellValidating(object sender,
        DataGridViewCellValidatingEventArgs e)
    {
        // Validate the CompanyName entry by disallowing empty strings.
        if (dataGridView1.Columns[e.ColumnIndex].Name == "CompanyName")
        {
            if (e.FormattedValue == null && 
                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;
    }
    

測試應用程式

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

若要測試表單

  • 編譯及執行應用程式。

    您將看到一個 DataGridView,其中填入了來自 Customers 資料表的資料。當您在 CompanyName 資料行的其中一個儲存格按兩下時,您就可以編輯其值。如果您刪除了所有字元,並且按 TAB 鍵試圖離開儲存格,DataGridView 會阻止您離開儲存格。在您於儲存格中輸入了非空字串之後,DataGridView 控制項就會讓您離開儲存格。

後續步驟

這個應用程式讓您對 DataGridView 控制項的功能有了初步的了解。您可以用許多方式來自訂 DataGridView 控制項的外觀和行為:

請參閱

工作

HOW TO:驗證 Windows Form DataGridView 控制項中的資料

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

概念

保護連接資訊 (ADO.NET)

參考

DataGridView

BindingSource

其他資源

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