備註
ToolStrip 控制項會取代 ToolBar 控制項並加入其他功能,不過您也可以選擇保留 ToolBar 控制項,以提供回溯相容性及未來使用。 如需詳細資訊,請參閱 Windows Forms DataGridView 和 DataGrid 控制項之間的差異。
Windows Forms DataGrid 控制項有兩種可用的輸入驗證。 如果使用者嘗試輸入的值,是儲存格不可接受的資料類型,例如將字串輸入到整數中,則會使用舊值取代新的無效值。 這種輸入驗證會自動完成,而且無法加以自訂。
其他類型的輸入驗證可用來拒絕任何不可接受的資料,例如欄位中必須大於或等於 1 的 0 值,或是不適當的字串。 這會藉由撰寫 ColumnChanging 或 RowChanging 事件的事件處理常式,在資料集中完成。 下列範例會使用 ColumnChanging 事件,因為「產品」資料行特別不允許使用不可接受的值。 您可以使用 RowChanging 事件,來檢查「結束日期」資料行的值是否晚於相同資料列中的「開始日期」資料行。
驗證使用者輸入
撰寫程式碼來處理適當資料表的 ColumnChanging 事件。 偵測到不適當的輸入時,呼叫 DataRow 物件的 SetColumnError 方法。
Private Sub Customers_ColumnChanging(ByVal sender As Object, _ ByVal e As System.Data.DataColumnChangeEventArgs) ' Only check for errors in the Product column If (e.Column.ColumnName.Equals("Product")) Then ' Do not allow "Automobile" as a product. If CType(e.ProposedValue, String) = "Automobile" Then Dim badValue As Object = e.ProposedValue e.ProposedValue = "Bad Data" e.Row.RowError = "The Product column contains an error" e.Row.SetColumnError(e.Column, "Product cannot be " & _ CType(badValue, String)) End If End If End Sub//Handle column changing events on the Customers table private void Customers_ColumnChanging(object sender, System.Data.DataColumnChangeEventArgs e) { //Only check for errors in the Product column if (e.Column.ColumnName.Equals("Product")) { //Do not allow "Automobile" as a product if (e.ProposedValue.Equals("Automobile")) { object badValue = e.ProposedValue; e.ProposedValue = "Bad Data"; e.Row.RowError = "The Product column contains an error"; e.Row.SetColumnError(e.Column, "Product cannot be " + badValue); } } }將事件處理常式連接到事件。
將下列程式碼放在表單 Load 的事件或其建構函式內。
' Assumes the grid is bound to a dataset called customersDataSet1 ' with a table called Customers. ' Put this code in the form's Load event or its constructor. AddHandler customersDataSet1.Tables("Customers").ColumnChanging, AddressOf Customers_ColumnChanging// Assumes the grid is bound to a dataset called customersDataSet1 // with a table called Customers. // Put this code in the form's Load event or its constructor. customersDataSet1.Tables["Customers"].ColumnChanging += new DataColumnChangeEventHandler(this.Customers_ColumnChanging);