Click here to Skip to main content
15,038,451 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
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!



VB
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
Posted
Comments
TnTinMn 14-Aug-13 12:30pm
   
Two things.
First it is best to remove the empty rows from the underlying data source (a datatable?).

Second, you can not modify the Rows collection while enumerating it. Instead use For-Next or Do-While loop to loop through the Rows from last to first and remove the empty rows.
Shahan Ayyub 14-Aug-13 14:58pm
   
Hi! As you said "it doens't seem to work properly for whatever reason", what is expected to you. current code is expected to remove the whole row if it is completely empty. Cell is somewhat is an interaction of a row and a column so you can either remove row or delete a column. What else do you expect ?

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900