0

Currently I have my program hiding blank or empty datagridview cells. I want to find a way to delete these cells entirely. The reason being, after the blank cells were hidden they would reappear after going through some of my other validations. These validations checked to see if the cells contained any invalid input such as negative numbers,non-numeric input and blank cells. If they contained any of the above they would be populated with default values, thus making my hidden cells reappear. Hopefully if there is a way to delete these cells they won't have a change of getting filled with default data. I've found the below code on MSDN but it doens't seem to work properly for whatever reason. Also I'm using the DATABINDINGCOMPLETE event. I'm not sure if there is another event that would work better for this situation. I greatly appreciate any help you may give!

   Private Sub DataGridView1_DataBindingComplete(sender As Object, e As DataGridViewBindingCompleteEventArgs) Handles DataGridView1.DataBindingComplete


    Dim i As Integer = 0
    Dim mtCell As Integer = 0
    For Each row As DataGridViewRow In DataGridView1.Rows
        For j = 1 To row.Cells.Count -2
            If row.Cells(j).Value Is DBNull.Value Then
                mtCell += 1
            End If
        Next
        If mtCell = row.Cells.Count Then
            DataGridView1.Rows.RemoveAt(i)
        End If
        i += 1
        mtCell = 0
    Next

end sub
4

1 回答 1

1

您的代码存在各种问题。在这里,您有一个改进的版本,应该可以正常工作:

Dim mtCell As Integer = 0
Dim row As DataGridViewRow = New DataGridViewRow()
For rowNo As Integer = DataGridView1.Rows.Count - 2 To 0 Step -1
    row = DataGridView1.Rows(rowNo)
    Try
        For j = 0 To row.Cells.Count - 2 
            If row.Cells(j).Value Is Nothing OrElse row.Cells(j).Value Is DBNull.Value Then
                mtCell += 1
            End If
        Next
        If mtCell = row.Cells.Count - 1 Then 'I understand that you want to delete the row ONLY if all its cells are null 
            DataGridView1.Rows.RemoveAt(rowNo)
        End If
        mtCell = 0
    Catch ex As Exception
        Exit For
    End Try
Next rowNo

首先,最好在删除时“向后”迭代 Collection 以避免出现问题(例如:3 行;您删除第一个位置,循环转到第二个位置;但删除后所有行“向上移动” " 因此第二个位置现在被第三行占据 -> 您将跳过第二行,最终迭代超出集合的限制)。DBNull.Value是相当严格的;不确定它在您的特定条件下是否正常工作,但最好用Nothing. 您不能影响For Each循环中正在迭代的项目(不太可能在正常情况下For一); 在这种情况下,您会间接影响它,但只是为了确保更好地依赖正常的 For 循环。您正在遍历行,但不是删除这些行,而是由计数器 ( i) 定义的行,它不一定与当前行号相关,最好摆脱它。最后,我添加了一个try...catch以确保(您不会访问不存在的职位)。

于 2013-08-14T15:15:18.043 回答