简体   繁体   中英

How to check if Cell In Datagridview has a value and continue VB.Net

hi my code is trying to

  • First: Find if value is in a Column 0 "CODE"

  • Second: If found check if Column 1 "STATUS" has value of "IN" If true MsgBox Appears with Message "Ticket Used" If Value is nothing then Change value to IN

this is my code:

    Private Sub changefound()

    Dim findtxt As String = txt_Find.Text
    Try
        If DataGridView2.Rows.Count > 0 Then
            For i As Integer = 0 To DataGridView2.Rows.Count - 1
                ' For j As Integer = 0 To DataGridView2.Columns.Count - 1 'Not using this because we only want to look in CODE column.
                Dim CellChange As String = DataGridView2.Rows(i).Cells("CODE").Value.ToString

                If CellChange.Contains(findtxt) = True Then
                    If DataGridView2.Rows(i).Cells("STATUS").Value = "IN" Then    'This is Line 366
                        MsgBox("Tickets USed")
                        Exit Sub


                    Else
                        With DataGridView2
                            ' .Rows(i).Cells(j).Style.BackColor = Color.Gray
                            '  .Rows(i).Cells(j).Value = findtxt
                            ' MsgBox(i & j + 1)

                            .Rows(i).Cells("STATUS").Value = "IN"


                            Exit Sub
                        End With
                    End If
                End If
                    'Next   'This is the Jfor 
            Next
        End If
    Catch e As Exception
        MessageBox.Show(e.ToString())
    End Try


End Sub

any way i move it around it will check only if IN is found will it MSGBox used ticket. If cell has no value it locks up with error:

System.InvalidCastException:Operator'=' is not defined for type"DBNull" and string "IN"
At main.vb:line366

any help?

Add DbNull checking before doing the comparison :

.....
If Not IsDbNull(DataGridView2.Rows(i).Cells("STATUS").Value) _
        AndAlso DataGridView2.Rows(i).Cells("STATUS").Value = "IN" Then 
.....

Read the following thread for more options to handle DbNull data : handling dbnull data in vb.net

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM