beginnerVB.Net beginnerVB.Net - 1 year ago 74 Question

Don't Add Value If Already Exists In Datagridview

I have a "table_info" table with a column for ID,NAME
When Adding new ID,Name. I would like to check if it's already exists. and If it exists, produce a MessageBox.

How can this be done

Answer Source

There is more than one way to accomplish this. You could check the datasource/set or the actual datagridview itself, if you don't have too many rows. If it's the later then you could do it like so:

Check Function returned true if the criteria is met:

    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

    Return isFound

End Function


Then to use the Function to display a MessageBox if the criteria is met:

    If (IsInDatagridview("id", "name", 0, 1, DataGridView1)) Then

        ''// Code to display message.
        MsgBox("Record Exists!", MsgBoxStyle.Information)

    End If

You may need to change The ID to an integer but I reckon it should work. Haven't tested it.

Okay so what this will do is iterate through each row 'rw' within the datagridview you specify, checking for String matches of the cell's columns' and if a match is found 'isFound' is set to true then 'isFound' is returned.