在整个Datagrid中搜索值

时间:2013-03-12 12:19:50

标签: .net vb.net winforms visual-studio-2010

如果国家/地区已经出现在数据网格中,我希望阻止用户将国家/地区添加到数据库。

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

2 个答案:

答案 0 :(得分:0)

您可以使用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

答案 1 :(得分:0)

尝试以下方法:

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”。我认为这可能是导致代码出现问题的原因。我希望这有帮助