1. 程式人生 > >DataGridView使用技巧十二:DataGridView Error圖標表示的設定

DataGridView使用技巧十二:DataGridView Error圖標表示的設定

needed errors 但是 應該 就會 aso void private pass

為了提醒用戶註意,DataGridView可以使用Error圖標來突出顯示。

Error圖標可以在單元格和行頭內表示,但不能在列頭上顯示。

1、ErrorText屬性

當設定單元格/行的ErrorText屬性的內容後,單元格/行的Error圖標就會被表示出來。另外,只有在DataGridView.ShowCellErrors=True時,Error圖標才能顯示。(默認屬性為True)

設定(0,0)的單元格表示Error圖標

1 this.dgv_Users[0, 0].ErrorText = "只能輸入男或女";

設定第4行的行頭顯示Error圖標

1 this.dgv_Users.Rows[3].ErrorText = "
不能輸入負數";

2、CellErrorTextNeeded、RowErrorTextNeeded事件

即時輸入時的Error圖標的表示,可以使用CellErrorTextNeeded事件。同時,在大量的數據處理時,需要進行多處的內容檢查並顯示Error圖標的應用中,遍歷單元格設定ErrorText的方法是效率低下的,應該使用CellErrorTextNeeded事件。行的Error圖標的設定則應該使用RowErrorTextNeeded事件。但是,需要註意的是當DataSource屬性設定了VirtualMode=True時,上述事件則不會被觸發。

CellErrorTextNeeded、RowErrorTextNeeded事件一般在需要保存數據時使用,保存數據之前先判斷單元格輸入的值是否合法,如果不合法,則在不合法的單元格或行顯示Error圖標。相當於做了一個客戶端的驗證。

 1 private void dgv_Users_CellErrorTextNeeded(object sender, DataGridViewCellErrorTextNeededEventArgs e)
 2 {
 3             DataGridView dgv=sender as DataGridView;
 4             
 5             if (dgv.Columns[e.ColumnIndex].Name.Equals("Sex"))
 6             {
 7                 string value = dgv[e.ColumnIndex, e.RowIndex].Value.ToString();
8 if (!value.Equals("") && !value.Equals("")) 9 { 10 e.ErrorText = "只能輸入男或女"; 11 } 12 } 13 }
1 private void dgv_Users_RowErrorTextNeeded(object sender, DataGridViewRowErrorTextNeededEventArgs e)
2 {
3             DataGridView dgv = sender as DataGridView;
4             if (dgv["UserName", e.RowIndex].Value == DBNull.Value && dgv["Password", e.RowIndex].Value == DBNull.Value)
5             {
6                 e.ErrorText = "UserName和Password列必須輸入值";
7             }
8 }

DataGridView使用技巧十二:DataGridView Error圖標表示的設定