vb.net 如何检查Datagridview中的单元格是否有值并继续VB.Net

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29323016/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 18:56:02  来源:igfitidea点击:

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

vb.netdatagridview

提问by db35m

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

  • 第一:查找值是否在第 0 列“代码”中

  • 第二:如果找到,请检查第 1 列“STATUS”的值是否为“IN” 如果为 true MsgBox 出现消息“Ticket Used” 如果值为空则将值更改为 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:

无论我如何移动它,它只会检查是否找到了 IN,它是否会使用 MSGBox 使用的票证。如果单元格没有值,它会锁定错误:

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

System.InvalidCastException:Operator'=' 未为类型“DBNull”和字符串“IN”定义
在 main.vb:line366

any help?

有什么帮助吗?

回答by har07

Add DbNullchecking before doing the comparison :

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

.....
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 DbNulldata : handling dbnull data in vb.net

阅读以下线程以获取更多处理DbNull数据的选项: 在 vb.net 中处理 dbnull 数据