0

如果国家/地区已出现在 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
4

2 回答 2

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
于 2013-03-12T12:31:07.363 回答
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”。我认为这可能是导致您的代码出现问题的原因。我希望这有帮助

于 2013-03-13T17:45:07.410 回答