【发布时间】:2013-03-12 12:19:50
【问题描述】:
如果国家/地区已出现在 Datagrid 中,我希望阻止用户将国家/地区添加到数据库中。
Datagrid 在表单加载事件中预加载了国家/地区。
我有以下代码(如下),但是我收到一条错误消息,指出下标超出范围且不能为负数。
Dim appear As Integer
Dim colcount As Integer
Dim rowcount As Integer
colcount = all_countries.ColumnCount
rowcount = all_countries.RowCount
For i = 0 To rowcount
For j = 0 To colcount
If (new_country.Text = all_countries.Item(colcount, rowcount).Value) Then
MsgBox("Country Exists", 0)
appear = 1
End If
Next
Next
【问题讨论】:
-
如果您使用数据表而不是数据网格搜索它会更简单。 For Each d as DataRow in datatable.Rows If d("Country) = ...
-
除了 OwerFlov 所述之外,当您应该迭代到 ColumnCount -1 和 RowCount -1 时,您正在枚举到 ColumnCount 和 RowCount,因为它们是基于 0 的索引。而且您不是只有一列用于国家/地区吗?为什么必须搜索所有列?
-
@OwerFlov:+1。您永远不应该直接在 UI 元素中执行验证。另一个想法是,您可以在该基础表上定义唯一键约束。然后就没有代码了。 :)
标签: .net vb.net winforms visual-studio-2010