【问题标题】:Searching a whole Datagrid for a Value在整个数据网格中搜索值
【发布时间】: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


【解决方案1】:

您可以使用CellValidating 事件,例如:

Private Sub all_countries_CellValidating(sender As Object, e As System.Windows.Forms.DataGridViewCellValidatingEventArgs) Handles all_countries.CellValidating
    Dim headerText = all_countries.Columns(e.ColumnIndex).HeaderText
    ' Abort validation if cell is not in the country column '
    If Not headerText.Equals("Country") Then Return

    ' Confirm that the cell is not empty '
    Dim thisCountry As String = e.FormattedValue.ToString()
    If String.IsNullOrEmpty(thisCountry) Then
        all_countries.Rows(e.RowIndex).ErrorText = "Country must not be empty"
        e.Cancel = True
    Else
        For Each row As DataGridViewRow In all_countries.Rows
            If row.Index <> e.RowIndex Then
                Dim countryCell = row.Cells(e.ColumnIndex)
                If thisCountry = countryCell.FormattedValue.ToString() Then
                    all_countries.Rows(e.RowIndex).ErrorText = "Country must be unique"
                    e.Cancel = True
                    Exit For
                End If
            End If
        Next
    End If
End Sub

【讨论】:

  • 我不太确定这一点。我不让用户直接添加到 Datagrid 中。他们在文本框 (new_country) 中输入他们的国家,然后通过按钮提交。原帖中的代码在按钮点击事件上。
  • @user1662306:这有关系吗?选择上面我在网格中搜索给定值的代码。但是,通常您应该更喜欢搜索底层数据源(例如数据库)。
【解决方案2】:

尝试以下方法:

Dim X as Integer
For X = 0 to DataGridView.Rows.Count - 1
   If DataGridView.Rows(X).Cells("ColumnName").Value = new_country.Text Then
      MsgBox("Country Exists", 0)
      appear = 1
   End If
Next

注意:“计数 - 1”。我认为这可能是导致您的代码出现问题的原因。我希望这会有所帮助

【讨论】:

    猜你喜欢
    • 2013-12-17
    • 2012-07-03
    • 2021-10-29
    • 1970-01-01
    • 2013-12-13
    • 1970-01-01
    • 2011-04-16
    • 1970-01-01
    • 2012-09-27
    相关资源
    最近更新 更多