2016-08-31 121 views
1

我的數據網格視圖包含一列。 DataGridView許多行是空的我正在使用循環刪除這些行。使用LOOP刪除Datagridview行

For j = 0 To DataGridView1.RowCount - 1   
    If DataGridView1.Rows(j).Cells(0).Value.ToString.Length = 0 Then 
     DataGridView1.Rows.RemoveAt(j) 
    End If 
Next 

錯誤:索引超出範圍。必須是非負數,並且小於集合的大小 。

在此先感謝!

回答

3

與C#不同,在VB.NET中,For循環的上限值爲only once in the beginning of the loop,並且在每次循環迭代中都不重新評估。您可以從最後一行開始循環以避免此問題:

For j = DataGridView1.RowCount - 1 To 0 Step -1 
    If DataGridView1(0, j).Value = "" Then DataGridView1.Rows.RemoveAt(j) 
Next