2013-03-12 68 views
0

我期望阻止用戶向數據庫添加國家(如果該國家已經出現在Datagrid中)。在整個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 
+2

如果您使用數據表而不是數據網格進行搜索,這會更簡單。如果d(「Country)= ... – Jaxedin 2013-03-12 12:24:20

+1

除了OwerFlov的狀態之外,當您應該迭代到ColumnCount -1和RowCount -1時,您會直接嘗試ColumnCount和RowCount,因爲它們是基於0的索引,你不是隻有一個國家的列?爲什麼要搜索所有的列? – APrough 2013-03-12 14:50:34

+0

@OwerFlov:+1。你不應該直接在UI元素中進行驗證,另一個想法是你可以有沒有代碼:) – Neolisk 2013-03-13 18:18:24

回答

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 
+0

即時消息不太確定,我不讓用戶直接添加到Datagrid中,他們在文本框(new_country)中輸入自己的國家,然後通過按鈕提交。原始帖子中的代碼在按鈕單擊事件上。 – user1662306 2013-03-12 12:43:17

+0

@ user1662306:這是否重要?選擇上面的代碼,我在網格中搜索給定值。 ou應該更喜歡搜索基礎數據源(例如,一個數據庫)。 – 2013-03-12 12:53:32

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」。我認爲這可能是你的代碼中導致問題的原因。我希望這可以幫助