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

當您向使用者顯示資料輸入功能時,您經常必須驗證輸入至表單的資料。 類別 DataGridView 提供在資料認可至資料存放區之前執行驗證的便利方式。 您可以藉由處理 CellValidating 事件來驗證資料,此事件是由 目前資料格變更時引發 DataGridView 的。

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

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

    此程式碼範例會使用傳 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.
        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 的事件實作處理常式,以初始化 DataGridView 和 並 BindingSource 設定資料系結。

    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 儲存格的值是否為空白的位置。 如果儲存格值驗證失敗,請將 Cancel 類別的 System.Windows.Forms.DataGridViewCellValidatingEventArgs 屬性設定為 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
    

測試應用程式

您現在可以測試表單,以確保其如預期般運作。

測試表單

  • 編譯並執行應用程式。

    您會看到 DataGridView 填滿資料表的資料 Customers 。 當您按兩下資料行中的資料 CompanyName 格時,您可以編輯值。 如果您刪除所有字元並按 TAB 鍵結束儲存格,則 DataGridView 會防止您結束。 當您在儲存格中輸入非空白字串時, DataGridView 控制項可讓您結束儲存格。

後續步驟

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

另請參閱