对象引用未设置为循环对象的实例

时间:2014-07-18 16:41:52

标签: asp.net vb.net gridview nullreferenceexception

我试图隐藏gridview的null或空列,当我调试时,在第一个for循环中它会抛出未设置为对象实例的对象引用。我已经尝试了一段时间,但我无法弄明白。这是我的代码。

Protected Sub GridView1_RowDataBound(ByVal sender As Object, 
            ByVal e As GridViewRowEventArgs)
    Dim Grid As GridView = FormView1.FindControl("GridView1")

    Dim hasData As Boolean = False
    Dim row As Integer

    For col = 0 To Grid.HeaderRow.Cells.Count Step 1

        For row = 0 To Grid.Rows.Count Step 1

            If Not (String.IsNullOrEmpty(Grid.Rows(row).Cells(col).Text)) Then
                hasData = True
            End If

        Next

        Grid.Columns(col).Visible = hasData
    Next

End Sub

2 个答案:

答案 0 :(得分:0)

你错过了一些重要的部分。这里有一些东西供你查看,看看你是否得到它。

             For Each clm As DataGridViewColumn In grdView.Columns
                Dim notAvailable As Boolean = True

                For Each row As DataGridViewRow In grdView.Rows
                    If Not String.IsNullOrEmpty(row.Cells(clm.Index).Value.ToString()) Then
                        notAvailable = False
                        Exit For
                    End If
                Next
                If notAvailable Then
                    grdView.Columns(clm.Index).Visible = False
                End If
            Next

答案 1 :(得分:0)

尝试这样的事情。如果列中的所有行都为空,则该列将被隐藏。因此,如果列中甚至有一个数据可用,则不会隐藏它。此代码假定您在gridview中拥有所有绑定列。

您可以在gridview的DataBound()事件后调用此方法,但无需进入RowDataBound()事件。

GridView1.DataSource = getGridDate() // your data source
GridView1.DataBind()
HideEmptyColumns ()

HideEmptyColumns ()方法

Private Sub HideEmptyColumns()
    Dim bHasValue As Boolean
      For iCol As Integer = 0 To GridView1.ColumnCount - 1
        bHasValue = False
        For iRow As Integer = 0 To GridView1.RowCount - 1
            If GridView1.Rows(iRow).Cells(iCol).Text != String.Empty Then
                bHasValue = True
                Exit For
            End If
        Next

        'Hide the column
        If bHasValue = False Then
            GridView1.Columns(iCol).Visible = False
        End If
    Next

End Sub