如何检查Cell In Datagridview中是否有值并继续VB.Net

时间:2015-03-28 21:48:41

标签: vb.net datagridview

我的代码正在尝试

  • 首先:查找值是否在第0列" CODE"

  • 第二:如果找到,请检查第1列和第34列;状态"具有" IN"的价值            如果为真,则MsgBox显示消息"使用票证"            如果值为空,则将值更改为IN

这是我的代码:

    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

任何方式我移动它只会检查是否找到了它将MSGBox使用的票。 如果单元格没有值,则会锁定错误:

  

System.InvalidCastException:操作' ='未定义类型" DBNull"   和字符串" IN"
  在   main.vb:line366

任何帮助?

1 个答案:

答案 0 :(得分:4)

在进行比较之前添加DbNull检查:

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

阅读以下主题以获取处理DbNull数据的更多选项: handling dbnull data in vb.net