locked
Gridview - hide columns in 75 columns dynamically RRS feed

  • Question

  • User363578564 posted

    The GV has 75 columns, many columns are blank dynamically, I wish to show only those columns have value

    However there is "insufficient stack exception" error when running the following code with the total number of columns more than 65.  It is OK when less.

    Grateful for any advice?  Thanks.

        Private Sub GV1_DataBound(sender As Object, e As EventArgs) Handles GV1.DataBound
            If sender.Rows.Count > 0 Then
                For i = 0 To sender.Columns.Count - 1
                    Dim havetext As Boolean = False
                    For a = 0 To sender.Rows.Count - 1
                        If sender.Rows(a).Cells(i).Text <> "&nbsp;" Then
                            havetext = True
                        End If
                    Next
                    If havetext = False Then
                        sender.Columns(i).Visible = False
                    End If
                Next
            End If
        End Sub

    Monday, November 12, 2018 3:26 AM

All replies

  • User-893317190 posted

    Hi TW88,

    You could try to use  OnRowDataBound and OnDataBound event.

    Below is my code.

     Private record(74) As Int32   'use an array to record the columns
        Protected Sub GridView1_RowDataBound(sender As Object, e As GridViewRowEventArgs)
            If e.Row.RowType = DataControlRowType.DataRow Then
                For index = 0 To e.Row.Cells.Count - 1
    
                    If e.Row.Cells(index).Text <> "&nbsp;" Then
                        record(index) = 1   'record the column which has text
                    End If
                Next
            End If
        End Sub
    
        Protected Sub GridView1_DataBound(sender As Object, e As EventArgs)
            For index = 0 To record.Count - 1
                If record(index) = 0 Then
                    GridView1.Columns(index).Visible = False  ' make the empty column invisible
                End If
    
            Next
        End Sub

    Or you could  add break keyword in your code so that it will not loop through all rows.

      Private Sub GV1_DataBound(sender As Object, e As EventArgs) Handles GV1.DataBound
            If sender.Rows.Count > 0 Then
                For i = 0 To sender.Columns.Count - 1
                    Dim havetext As Boolean = False
                    For a = 0 To sender.Rows.Count - 1
                        If sender.Rows(a).Cells(i).Text <> "&nbsp;" Then
                            havetext = True
    Exit For End If Next If havetext = False Then sender.Columns(i).Visible = False End If Next End If End Sub

    Best regards,

    Ackerly Xu

    Tuesday, November 13, 2018 4:13 AM
  • User363578564 posted

    Thanks a lot.

    Finally, the code is moved from GV databound to Dropdownlist selectedindexchanged

    not sure whether the limit of GV or databound. 

    Tuesday, November 13, 2018 6:45 AM