简体   繁体   English

如何在vb.net中检查datacolumn是否包含值

[英]how to check datacolumn contains value or not in vb.net

I have dataset having 6 column from which I have added values in any three column. 我有6列的数据集,从中我在任何三列中添加了值。 so before binding Dataset to Grid, I want to remove the column which do not contain any value in vb.net 所以在将数据集绑定到网格之前,我想删除vb.net中不包含任何值的列

For Each column As DataColumn In dt.Columns
    If column Is Nothing OrElse IsDBNull(column) OrElse Convert.DBNull(column) Then
        dt.Columns.Remove(column)
    End If
Next

To find the columns that contains only null values you will need to nest two loops together, one for the columns and one for the rows. 要查找仅包含空值的列,您需要将两个循环嵌套在一起,一个循环用于列,一个循环用于行。 To remove the columns from the datatable I suggest adding the columns that contains only null to a List of DataColumn and only once you've iterated all columns remove them, Otherwise the loop for the columns might not work properly. 要从数据表中删除列,我建议将仅包含null的列添加到DataColumn列表中,并且只有在迭代所有列后才将它们删除,否则列的循环可能无法正常工作。

Try something like this: 尝试这样的事情:

Dim ValueFound as boolean
Dim ColumnsToRemove as new List(Of DataColumn)
Dim dt as DataTable = MyDataSet.Tables(0)
For Each Column as DataColumn in dt.Columns
    ValueFound = false
    For Each Row as DataRow in dt.Rows
        if Not Row(Column.Name) Is Nothing AndAlso Not IsDBNull(Row(Column.Name)) Then
            ValueFound = True
            Exit For
        End if
    Next
    If Not ValueFound Then
        ColumnsToRemove.Add(Column)
    End If
Next

For Each Column As DataColumn IN ColumnsToRemove
    dt.Columns.Remove(Column)
Next

Note: Code was written directly here, there might be some mistakes. 注意:代码是直接在此处编写的,可能会有一些错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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