Question : Deleting empty columns in dataset

Experts -

I have a dataset returned from SQL Server that I dump into Excel. Before I dump it into Excel, however, I delete any columns that are empty. Unfortunately, this code is a bit buggy - I can't tell why, but on larger volumns of data (that is, a greater number of rows), it doesn't seem to be working. Here's the code snippet:

Dim da As New SqlClient.SqlDataAdapter
Dim ds As New DataSet

                        Dim intColumn, intRow, intColumnValue As Integer
                        Dim strExcelFile As String
                        Dim strFileName As String
                        Dim cn As New SqlConnection(strConn)

                        da.SelectCommand = New SqlClient.SqlCommand(strsql, cn)
                        da.SelectCommand.CommandTimeout = 0
                        da.Fill(ds, "Qry")
                       
    'here we delete any empty columns from the datatable
                            For i As Integer = ds.Tables(0).Columns.Count - 1 To 0 Step -1
                                If ds.Tables(0).Columns(i).DataType Is GetType(String) Then
                                    ds.Tables(0).DefaultView.RowFilter = ds.Tables(0).Columns(i).Caption & "=''"
                                    If ds.Tables(0).DefaultView.Count = ds.Tables(0).Rows.Count Then
                                        ds.Tables(0).Columns.RemoveAt(i)
                                    End If
                                End If
                            Next

Any help would be greatly appreciated.

TIA,
crafuse

Answer : Deleting empty columns in dataset

Sure, here it is:

'here we delete any empty columns from the datatable
For i As Integer = ds.Tables(0).Columns.Count - 1 To 0 Step -1

    If ds.Tables(0).Columns(i).DataType Is GetType(String) Then

        'Replacement made here
        'ds.Tables(0).DefaultView.RowFilter = ds.Tables(0).Columns(i).Caption & "=''"    

        Dim colName As String =  ds.Tables(0).Columns(i).ColumnName
        ds.Tables(0).DefaultView.RowFilter = colName & " = '' or " & colName & " is null"


        If ds.Tables(0).DefaultView.Count = ds.Tables(0).Rows.Count Then _
            ds.Tables(0).Columns.RemoveAt(i)

    End If

Next
Random Solutions  
 
programming4us programming4us