积极答复者
MSDN上的一个程序段,怎么觉得好像不太对劲儿?“验证 Windows 窗体 DataGridView 控件中的数据”中的一个问题

问题
-
下面这段程序
Private Sub dataGridView1_CellValidating(ByVal sender As Object, _ ByVal e As DataGridViewCellValidatingEventArgs) _ Handles dataGridView1.CellValidating ' Validate the CompanyName entry by disallowing empty strings. If dataGridView1.Columns(e.ColumnIndex).Name = "CompanyName" Then If e.FormattedValue IsNot Nothing AndAlso _ String.IsNullOrEmpty(e.FormattedValue.ToString()) Then dataGridView1.Rows(e.RowIndex).ErrorText = _ "Company Name must not be empty" e.Cancel = True End If End If End Sub
原贴地址:
http://msdn.microsoft.com/zh-cn/library/ykdxa0bc.aspx
问题就是在最内层的If 语句e.FormattedValue 就是Nothing的话这个If语句好像是执行不了的。因为AndAlso第一项为False就不会判断第二项了。
如果说用户就没有在某个单元格输入数据,e.FormattedValue就是Nothing的话,那么这个程序段应该有问题。不知道我这样理解对不对。如果说我理解的不正确,那么什么情况下e.FormattedValue 是Nothing?
谢谢
答案
-
没问题
Private Sub DataGridView1_CellValidating(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellValidatingEventArgs) Handles DataGridView1.CellValidating
DataGridView1.Rows(e.RowIndex).Cells(e.ColumnIndex).ErrorText = "error"
End Sub
你跟踪看看是不是没走到你的if里去
http://feiyun0112.cnblogs.com/
全部回复
-
谢谢讲解。
如果说只有当e.FormattedValue为空字串的时候报msg。那么当e.FormattedValue没有值的时候呢?难道这种情况不应该报msg吗?
还有,ErrorText中的内容要怎样才能显示出来呢?我做了个相似的但是只能阻止错误,不能显示ToolTip。为什么呢?
Private Sub DataGridViewTest_CellValidating(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellValidatingEventArgs) Handles DataGridViewTest.CellValidating
Select Case Me.DataGridViewTest.Columns(e.ColumnIndex).Name
Case "Item"
If e.FormattedValue < 0 Then
DataGridViewTest.Rows(e.RowIndex).ErrorText = "Negative value is not allowed."
e.Cancel = True
End If
Case "Material"
'Nothing
End Select
End Sub
是不是这段程序(我知道e.FormattedValue < 0 不完整但这并不影响这个问题)还缺东西?
多谢指点。- 已编辑 VB必填字段 2009年6月24日 14:36
-
没问题
Private Sub DataGridView1_CellValidating(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellValidatingEventArgs) Handles DataGridView1.CellValidating
DataGridView1.Rows(e.RowIndex).Cells(e.ColumnIndex).ErrorText = "error"
End Sub
你跟踪看看是不是没走到你的if里去
http://feiyun0112.cnblogs.com/ -
谢谢解答。
让我学习学习啊,因为是崭新的新手,反应很慢。
另外就是msg的问题,我的Dialog上的DGV可以阻止错误输入(我修改代码为:DataGridViewTest.Rows(e.RowIndex).Cells(e.ColumnIndex).ErrorText = "Negative value is not allowed."),但是不现实那个叹号标志自然也就没有ErrorText可以显示了。
但是当我修改完成错误单元格后,反而出现了本应该在刚才出现的叹号标志。什么地方错了?我想是触发事件不对劲,我再看看。要是明白就直接告诉我吧。一个人啃真的很慢。还有就是MSDN上的那段程序能在输入错误时调出msg吗?我没有看出在这点上二段儿有本质的区别。
多谢指点。