Introduction
I faced a problem where I wanted to Show / Hide detailed information dynamically in a DataGridView
.
Background
I am developing a system which incorporates Routing information. In a section of the application, I wanted to provide the user an option between a General View and a Detailed View of the Routing information.
The General View would only show Route Leg information which is the Origin and the Destination, total distance and total Estimated Duration whereas the Detailed View will display the Steps for each Leg of the Route.
General View
Before.jpg
Detailed View
After.jpg
Using the Code
Originally, I focused on the DataGridView
's .
Rows.Count
and also .
RowCount
to try and loop through the rows in the DataGridView
.
The problem was that at loop execution, a "snapshot" of the row count was taken. This means that every time I Insert
new rows, the newly added rows will not be taken into account and it led to many different loop options which all failed - For Each...Next
, For...Next
and also While...End While
.
The problem was the "snapshot" and because I had no certainty that it was actually the problem, I took a different approach by not looping on the number of rows but instead of setting a trigger (True
/False
) when I have re-evaluated the number of rows to the current loop count (i += 1
).
The result was a perfect solution to the problem.
Below is the code implementation I am now using to achieve the goal of Show / Hide details dynamically.
Private Sub chkShowRouteStep_CheckedChanged(sender As Object, e As EventArgs) _
Handles chkShowRouteStep.CheckedChanged
Try
Dim lastRow As Boolean = False
Dim i As Integer = 0
If chkShowRouteStep.Checked Then
While lastRow <> True
If dgvQuote.Rows(i).Cells(0).Value.ToString <> "" Then
For j As Integer = 1 To 2
dgvQuote.Rows.Insert(i + j, "", "", "Step")
Next
End If
If i = dgvQuote.Rows.Count - 1 Then
lastRow = True
End If
i += 1
End While
Else
For x As Integer = dgvQuote.RowCount - 1 To 0 Step -1
If dgvQuote.Rows(x).Cells(2).Value.ToString = "Step" Then
dgvQuote.Rows.RemoveAt(x)
End If
Next
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
History
- 15th January, 2017: Initial version