2014-07-18 68 views
-4

我試圖隱藏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 
+0

在哪一行沒有這一點,爲什麼讓我們猜? – Plutonix

+1

循環直到計數到達不是一個好主意。循環直到(Count-1)。如果你調試程序崩潰,你會注意到行和列可能是我們的範圍。 –

+0

是的,我正確的數 - 1,我錯過了。 – user3841709

回答

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 
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 
相關問題