简体   繁体   中英

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. so before binding Dataset to Grid, I want to remove the column which do not contain any value in 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.

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.

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