Reputation: 1
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
Upvotes: 0
Views: 2284
Reputation: 82474
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.
Upvotes: 1