DataGridView 编程36计(二)
2008-02-26 09:47:39
① DataGridView Error图标表示的设定: GO TO TOP
为了提醒用户注意,DataGridView可以使用Error图标来突出显示。如下图: ![]() Error图标可以在单元格和行头内表示,但不能在列头上显示。 1) ErrorText属性 当设定单元格/行的ErrorText属性的内容后,单元格/行的Error图标就会被表示出来。另外,只有在DataGridView.ShowCellErrors = True时,Error图标才能显示。(默认即时True) [VB.NET] ' 设定 (0, 0) 的单元格表示 Error图标 DataGridView1(0, 0).ErrorText = "请确认单元格的值。" ' 设定第4行(Index=3)的行头显示Error图标 DataGridView1.Rows(3).ErrorText = "不能输入负值。" 2) CellErrorTextNeeded、RowErrorTextNeeded 事件 即时输入时的Error图标的表示,可以使用CellErrorTextNeeded事件 同时,在大量的数据处理时,需要进行多处的内容检查并显示Error图标的应用中。遍历单元格设定ErrorText的方法是效率低下的,应该使用CellErrorTextNeeded事件。行的Error图标的设定则应该用RowErrorTextNeeded事件。 但是,需要注意的是当DataSource属性设定了VirtualMode=True时,上述事件则不会被引发。 [VB.NET] 'CellErrorTextNeeded 事件处理方法 Private Sub DataGridView1_CellErrorTextNeeded(ByVal sender As Object, _ ByVal e As DataGridViewCellErrorTextNeededEventArgs) _ Handles DataGridView1.CellErrorTextNeeded Dim dgv As DataGridView = CType(sender, DataGridView) ' 单元格值为负整数时,Error图标被表示。 Dim cellVal As Object = dgv(e.ColumnIndex, e.RowIndex).Value If TypeOf cellVal Is Integer AndAlso CInt(cellVal) < 0 Then e.ErrorText = "不能输入负整数。" End If End Sub 'RowErrorTextNeeded 事件处理方法 Private Sub DataGridView1_RowErrorTextNeeded(ByVal sender As Object, _ ByVal e As DataGridViewRowErrorTextNeededEventArgs) _ Handles DataGridView1.RowErrorTextNeeded Dim dgv As DataGridView = CType(sender, DataGridView) If dgv("Column1", e.RowIndex).Value Is DBNull.Value AndAlso _ dgv("Column2", e.RowIndex).Value Is DBNull.Value Then e.ErrorText = _ "Column1和Column2必须输入一个值。" End If End Sub [C#] // CellErrorTextNeeded 事件处理方法 private void DataGridView1_CellErrorTextNeeded(object sender, DataGridViewCellErrorTextNeededEventArgs e) { DataGridView dgv = (DataGridView)sender; // 单元格值为负整数时,Error图标被表示。 object cellVal = dgv[e.ColumnIndex, e.RowIndex].Value; if (cellVal is int && ((int)cellVal) < 0) { e.ErrorText = "不能输入负整数。"; } } // RowErrorTextNeeded 事件处理方法 private void DataGridView1_RowErrorTextNeeded(object sender, DataGridViewRowErrorTextNeededEventArgs e) { DataGridView dgv = (DataGridView)sender; if (dgv["Column1", e.RowIndex].Value == DBNull.Value && dgv["Column2", e.RowIndex].Value == DBNull.Value) { e.ErrorText = "Column1和Column2必须输入一个值。"; } } 本文出自 51CTO.COM技术博客 |



zhcsmx22
博客统计信息
热门文章
最新评论
友情链接