當您向使用者顯示資料輸入功能時,經常必須驗證輸入至表單的資料。 DataGridView 類別提供一個便利方式,可在資料認可至資料存放區之前執行驗證。 您可以處理 CellValidating 事件來驗證資料,此事件是由 DataGridView 在目前的儲存格變更時引發。
在本逐步解說中,您將從 Northwind 範例資料庫中的 Customers 資料表擷取資料列,並將其顯示在 DataGridView 控制項中。 當使用者編輯 CompanyName 資料行中的儲存格並嘗試離開儲存格時,CellValidating 事件處理常式會檢查新的公司名稱字串,以確定其不是空白的;如果新值是空白字串,則 DataGridView 會使使用者的游標無法離開儲存格,直到輸入非空白字串為止。
若要將本主題中的程式碼複製為單一清單,請參閱如何:驗證 Windows Forms DataGridView 控制項中的資料 (英文)。
先決條件
為了完成這個逐步解說,您需要:
- 具有 Northwind SQL Server 範例資料庫的伺服器存取權。
建立表單
驗證 DataGridView 中輸入的資料
建立衍生自 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在表單的類別定義中實作方法,以處理連線到資料庫的詳細資料。
此程式碼範例會使用傳回填入 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. 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為表單的 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針對 DataGridView 控制項的 CellValidating 和 CellEndEdit 事件實作處理常式。
CellValidating 事件處理常式是您判斷
CompanyName資料行中儲存格的值是否為空白之處。 如果儲存格值驗證失敗,請將 System.Windows.Forms.DataGridViewCellValidatingEventArgs 類別的 Cancel 屬性設定為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 控制項的外觀和行為:
變更框線和標頭樣式。 如需詳細資訊,請參閱如何:變更 Windows Forms DataGridView 控制項中的框線和格線樣式 (英文)。
啟用或限制使用者輸入 DataGridView 控制項。 如需詳細資訊,請參閱如何:防止在 Windows Forms DataGridView 控制項中新增和刪除資料列 (英文),以及如何:使 Windows Forms DataGridView 控制項中的資料行成為唯讀 (英文)。
檢查使用者輸入是否有資料庫相關錯誤。 如需詳細資訊,請參閱逐步解說:處理 Windows Forms DataGridView 控制項中的資料輸入期間所發生的錯誤 (英文)。
使用虛擬模式處理非常大的資料集。 如需詳細資訊,請參閱逐步解說:在 Windows Forms DataGridView 控制項中實作虛擬模式 (英文)。
自訂儲存格的外觀。 如需詳細資訊,請參閱如何:在 Windows Forms DataGridView 控制項中自訂儲存格的外觀 (英文),以及如何:設定 Windows Form DataGridView 控制項的字型和色彩樣式 (英文)。