逐步解說:處理 Windows Form DataGridView 控制項中的資料輸入期間所發生的錯誤
處理基礎資料存放區的錯誤是資料輸入應用程式的必要功能。 Windows Forms DataGridView 控制項藉由公開 DataError 事件,讓此事件變得簡單,當資料存放區偵測到條件約束違規或商務規則中斷時,就會引發此事件。
在本逐步解說中,您將從 Northwind 範例資料庫中的 Customers
資料表擷取資料列,並將其顯示在控制項中 DataGridView 。 在新的資料列或編輯的現有資料列中偵測到重複 CustomerID
的值時, DataError 就會發生事件,這會藉由顯示 MessageBox 描述例外狀況的 來處理。
若要將本主題中的程式碼複製為單一清單,請參閱 如何:處理 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); }
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
在表單的類別定義中實作方法,以處理連線到資料庫的詳細資料。
此程式碼範例會使用傳
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, 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
為表單 Load 的事件實作處理常式,以初始化 DataGridView 和 並 BindingSource 設定資料系結。
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
DataError處理 上的 DataGridView 事件。
如果錯誤的內容是認可作業,請在 中 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 執行應用程式。
您會看到填 DataGridView 滿 Customers 資料表資料的控制項。 如果您輸入重複的值
CustomerID
並認可編輯,儲存格值會自動還原,而且您會看到 MessageBox 顯示資料輸入錯誤的 。
後續步驟
此應用程式可讓您對控制項的功能有基本的瞭解 DataGridView 。 您可以透過數種方式自訂控制項的外觀和行為 DataGridView :
變更框線和標題樣式。 如需詳細資訊,請參閱 如何:變更 Windows Forms DataGridView 控制項 中的框線和格線樣式。
啟用或限制使用者輸入控制項 DataGridView 。 如需詳細資訊,請參閱 How to: Prevent Row Addition and Deletion in the Windows Forms DataGridView Control , and How to: Make Columns Read-Only in the Windows Forms DataGridView Control .
驗證控制項的使用者輸入 DataGridView 。 如需詳細資訊,請參閱 逐步解說:驗證 Windows Forms DataGridView 控制項 中的資料。
使用虛擬模式處理非常大的資料集。 如需詳細資訊,請參閱 逐步解說:在 Windows Forms DataGridView 控制項 中實作虛擬模式。
自訂儲存格的外觀。 如需詳細資訊,請參閱 如何:自訂 Windows Forms DataGridView 控制項中的儲存格外觀和 如何:設定 Windows Forms DataGridView 控制項 的預設儲存格樣式。
另請參閱
意見反應
https://aka.ms/ContentUserFeedback。
即將登場:在 2024 年,我們將逐步淘汰 GitHub 問題作為內容的意見反應機制,並將它取代為新的意見反應系統。 如需詳細資訊,請參閱:提交並檢視相關的意見反應