检查Column是否为空

时间:2014-02-04 02:11:19

标签: .net database vb.net ms-access

我正在研究如何检查特定行的列数据。我发现了这个:

For Each row In tablePiglet.Rows ' - data table
        If Not DBNull.Value.Equals(row("CurrentLocation")) Then
            MessageBox.Show("Not Empty")
        Else
            MessageBox.Show("Empty")
        End If
    Next

我试图运行该应用程序,但代码未执行。我在For Each中添加了一个断点,但它刚刚结束。这是为什么?有关CurrentLocation字段的数据,因此它应显示为空。

我想要检查该行的CurrentLocation是否为空。
类似于:SELECT CurrentLocation FROM tableFoo WHERE id=1然后检查它是否为空。
上面的代码是正确的吗?还是有其他更好的方法吗?

3 个答案:

答案 0 :(得分:0)

试试这个:

    For Each _dtrow as DataRow In tablePiglet.Rows ' - data table
        If _dtrow.Item("CurrentLocation").toString IsNot Nothing Or
           _dtrow.Item("CurrentLocation").toString <> vbNullString Then

              MessageBox.Show("Not Empty")
        Else
              MessageBox.Show("Empty")

        End If
    Next

答案 1 :(得分:0)

如果您知道您只有一行,并且您知道它,因为在您的数据库中只有一行可能具有您指向的某个ID

SELECT CurrentLocation FROM tableFoo WHERE id=1

在这种情况下,你不需要循环,你知道,这是一行

If tablePiglet.Rows.Count > 0 Then
    If IsDbNull(tablePiglet.Rows(0)("CurrentLocation")) Then
        MessageBox.Show("Empty")
    Else
        MessageBox.Show("Not Empty")
    End If
End If

应该这样做

但如果你确实有很多行,那么创建List

Dim l as new List(of String)

For i as integer = 0 in tablePiglet.Rows.count-1

 If IsDbNull(tablePiglet.Rows(i)("CurrentLocation")) Then 
     l.Add(i.ToString())
 end if
next

if l.Count > 0 Then MessageBox.Show("Empty rows are " & string.Join(",", l.ToArray())

它将列出所有空行“CurrentLocation”

的行

答案 2 :(得分:0)

也许试试这个....我使用as Datagridviewrow

For Each row As DataGridViewRow In xDataGridView.Rows

   If row.Cells("CurrentLocation").Value Is Nothing Or row.Cells("CurrentLocation").Value Is DBNull.Value Then
       MessageBox.Show("Not Empty")
    Else
        MessageBox.Show("Empty")
   End If
Next
edi:我的坏人没有看到它在dt

但你的代码是正确的,所以其他东西必须弄乱它

edit2:你说,每个人都马上结束了......  我的猜测是空的,你检查了它的计数吗?