2011-07-14 24 views
1

請閱讀此代碼:GridView控件數據表:跳過某些列

Dim dt As New DataTable 

    For Each col As DataControlField In GridView1.Columns 
     dt.Columns.Add(col.HeaderText) 
    Next 

    For Each row As GridViewRow In GridView1.Rows 
     Dim nrow As DataRow = dt.NewRow 
     Dim z As Integer = 0 
     For Each col As DataControlField In GridView1.Columns 
      nrow(z) = row.Cells(z).Text.Replace(" ", "") 
      z += 1 
     Next 
     dt.Rows.Add(nrow) 
    Next 

我怎麼能跳過GridView控件的某些列?例如:第1列和第6列

謝謝所有爲您的時間!

回答

0
Dim dt As New DataTable 
For Each col As DataControlField In GridView1.Columns 
If (col.Index <> 1) and (col.Index <> 3) and (col.Index <> 6) then 
dt.Columns.Add(col.HeaderText) 
End If 
Next 
For Each row As GridViewRow In GridView1.Rows 
Dim nrow As DataRow = dt.NewRow 
Dim z As Integer = 0 
For Each col As DataControlField In GridView1.Columns 
If (col.Index <> 1) and (col.Index <> 3) and (col.Index <> 6) then 
nrow(z) = row.Cells(z).Text.Replace("&nbsp;", "") 
z += 1 
End If 
Next 
dt.Rows.Add(nrow) 
Next 

難道你不想接近你想要的嗎?

For-Each迭代器循環遍歷每個元素,並且可以如圖所示過濾不需要的元素。

或者,您可以創建一個您想要處理的所有索引的數組,並遍歷該數組以僅處理僅包含所需索引的列。