【问题标题】:Object Reference Not set to instance of an object for loop [duplicate]对象引用未设置为循环对象的实例[重复]
【发布时间】:2025-12-17 23:00:01
【问题描述】:

我试图隐藏 gridview 中为空或为空的列,当我调试时,在第一个 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

【问题讨论】:

  • 发生在哪一行,为什么让我们猜测?
  • 在达到 Count 之前循环不是一个好主意。循环直到 (Count-1)。如果你在程序崩溃的情况下调试程序,你会注意到 row 和 col 可能是我们的范围。
  • 是的,我更正了计数 - 1,我错过了。
  • 它试图引用的对象是什么?我正在尝试创建一个新的 gridview 实例,但这不是问题
  • 为什么要在GridView1_RowDataBound 内循环遍历Grid.Rows.CountRowDataBound 本身会为网格中的每一行执行,因此您无需再次循环。

标签: asp.net vb.net gridview nullreferenceexception


【解决方案1】:

试试这样的。如果一列中的所有行都为空,则该列将被隐藏。因此,即使一列中只有一个数据可用,它也不会被隐藏。此代码假定您在 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

【讨论】:

    【解决方案2】:

    您缺少一些重要的部分。这里有一些东西让你看看,看看你是否明白。

                 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
    

    【讨论】:

      最近更新 更多