我有一个“table_info”表,其中包含ID,NAME列 添加新ID时,名称。我想检查它是否已经存在。如果存在,则生成一个MessageBox。
如何做到这一点
答案 0 :(得分:1)
实现这一目标的方法不止一种。如果没有太多行,可以检查数据源/集或实际的datagridview本身。如果是晚些时候你就可以这样做:
如果符合条件,Check Function返回true:
Function IsInDatagridview(ByVal cell1 As String, ByVal cell2 As String, ByVal rowCell1_ID As Integer, ByVal rowCell2_ID As Integer, ByRef dgv As DataGridView)
Dim isFound As Boolean = False
For Each rw As DataGridViewRow In dgv.Rows
If rw.Cells(rowCell1_ID ).Value.ToString = cell1 Then
If rw.Cells(rowCell2_ID ).Value.ToString = cell2 Then
isFound = True
Return isFound
End If
End If
Next
Return isFound
End Function
然后,如果满足条件,则使用Function显示MessageBox:
If (IsInDatagridview("id", "name", 0, 1, DataGridView1)) Then
''// Code to display message.
MsgBox("Record Exists!", MsgBoxStyle.Information)
End If
您可能需要将ID更改为整数,但我认为它应该可以正常工作。没有测试过。
好的,这样做会迭代你指定的datagridview中的每一行'rw',检查单元格列的String匹配'如果找到匹配'isFound'设置为true则'isFound'是回。
答案 1 :(得分:1)
Ypu必须引用rowCell_ID
作为字符串,因为它是datagridivew中的列名:
Function IsInDatagridview(ByVal cell1 As String, ByVal cell2 As String, ByVal rowCell1_ID As Integer, ByVal rowCell2_ID As Integer, ByRef dgv As DataGridView)
Dim isFound As Boolean = False
For Each rw As DataGridViewRow In dgv.Rows
If rw.Cells("rowCell1_ID" ).Value.ToString = cell1 Then
If rw.Cells("rowCell2_ID" ).Value.ToString = cell2 Then
isFound = True
Return isFound
End If
End If
Next
Return isFound
End Function