DataGridView looping from bottom up - vb.net

When I run code below, the selected row returned is always from the bottom up. How can I get it to loop from the top of the Data Grid table each time?
'Find the selected customer by code. Display closest match in grid.
Dim targetString As String = txtAccountCode.Text
For Each row As DataGridViewRow In frmCustomerLookUp.GSCUSTDataGridView.Rows
If row.Cells(0).Value.ToString().StartsWith(targetString) Then
frmCustomerLookUp.GSCUSTDataGridView.ClearSelection()
frmCustomerLookUp.GSCUSTDataGridView.Rows(row.Index).Selected = True
frmCustomerLookUp.GSCUSTDataGridView.FirstDisplayedScrollingRowIndex = frmCustomerLookUp.GSCUSTDataGridView.SelectedRows(0).Index
Dim selectedIndex = frmCustomerLookUp.GSCUSTDataGridView.SelectedRows(0).Index
frmCustomerLookUp.GSCUSTDataGridView.Rows(selectedIndex).Selected = True
frmCustomerLookUp.GSCUSTDataGridView.Rows(selectedIndex).Cells(0).Selected = True
Exit Sub
End If
Next

Use a For...Next loop, starting at the last row and stepping -1
For index As Integer = frmCustomerLookUp.GSCUSTDataGridView.Rows.Count - 1 To 0 Step -1 ' Or Count -2
If frmCustomerLookUp.GSCUSTDataGridView.Rows(index).Cells(0).Value.ToString().StartsWith(targetString) Then

As the other person said. (Just a bit shorter)
For x=frmCustomerLookUp.GSCUSTDataGridView.Rows.Count - 1 To 0 Step -1
if frmCustomerLookUp.GSCUSTDataGridView(0,x).ToString().StartsWith(targetString) then
'something
end if
next

Related

CheckBox in DataGridView Won't Evaluate if Cell Has Focus

The first column in a DataGridView (dgv1) has checkboxes. Interestingly, when you click on the last checkbox desired, as soon a you loop through the rows for that column to evaluate checked items, the last cell checked (with a cursor on it) does not evaluate to true. The syntax for looping through the checkboxes in column 0 is below:
Dim NumCBChecked As Integer = 0
For i = 0 To dgv1.Rows.Count - 1
If CBool(dgv1(0, i).Value) = True Then
NumCBChecked += 1
End If
Next
Is there a way to set the focus to false if the cell containing the last checkbox checked is in edit mode?
BTW, refreshing the edit status (below) did not help before looping:
dgv1.RefreshEdit()
Per #JohnG's comment, the suggestion worked as follows:
dgv1.EndEdit()
Dim NumCBChecked As Integer = 0
For i = 0 To dgv1.Rows.Count - 1
If CBool(dgv1(0, i).Value) = True Then
NumCBChecked += 1
End If
Next

How to hide duplicate rows in a DataGridView?

I have a DataGridView in which I have transferred rows from another Form.
In my DataGridView I have three columns: the first one is name, the second is value, the third is id.
I want to hide duplicate rows with the same name and id.
How can I do this? My code is not working.
For i As Integer = 1 To Form.DataGridView1.Rows.Count - 1
If Form.DataGridView1.Rows(i).Cells(0).Value.ToString = Form.DataGridView1.Rows(i - 1).Cells(0).Value.ToString AndAlso
Convert.ToInt32(Form.DataGridView1.Rows(i).Cells(2).Value) = Convert.ToInt32(Form.DataGridView1.Rows(i - 1).Cells(2).Value) Then
Form.DataGridView1.Rows(i).Visible = False
End If
Next
You have only compared current row with current index-1 row. So, your code is not working. You need a nested loop to eliminate duplicate rows:
For i As Integer = 1 To Form.DataGridView1.Rows.Count - 1
For j As Integer = i - 1 To 0 Step -1
If Form.DataGridView1.Rows(i).Cells(0).Value.ToString = Form.DataGridView1.Rows(j).Cells(0).Value.ToString AndAlso
Convert.ToInt32(Form.DataGridView1.Rows(i).Cells(2).Value) = Convert.ToInt32(Form.DataGridView1.Rows(j).Cells(2).Value) Then
Form.DataGridView1.Rows(i).Visible = False
End If
Next
Next
Here is output

How do I loop through a DataGridView where RowCount / Rows.Count changes

I have a VB.Net Form with a DataGridView where I wish to change between a Detailed View and a General View.
The DataGridView shows the Distance and Estimated Time between places - called the Route Leg Data and is termed the General View
I have implemented a CheckBox to select between the general and detailed view. When the CheckBox is Checked, I am trying to loop through all of the Route Leg entries and insert the Route Steps which is the Detailed information about the Leg entries.
I have tried various loop options: For..Next, For Each...Next, While...End While, and only the first row (Route Leg) gets processed, even if I have 5 more Route Leg entries.
Important: Keep in mind that when the Detail View is selected, the DataGridView row count increments for every new Route Step entry that gets inserted.
I tried to use both dgv.RowCount and dgv.Rows.Count but I keep getting the same result.
I have added some code to show what I am trying to achieve. Any help or guidance will be much appreciated.
'Show / Hide Route Step Data
Private Sub chkShowRouteStep_CheckedChanged(sender As Object, e As EventArgs) Handles chkShowRouteStep.CheckedChanged
Try
If chkShowRouteStep.Checked Then
'Show Route Steps
For i As Integer = 0 To dgvQuote.RowCount - 1
txtRowCount.Text = i
If dgvQuote.Rows(i).Cells(0).Value.ToString <> "" Then
For j As Integer = 1 To 5
i += 1
dgvQuote.Rows.Insert(i, "Step")
'dgvQuote.Rows.Insert(j + i, "Step")
Next
End If
Next
Else
'Hide Route Steps - WORKS GREAT
For i As Integer = dgvQuote.RowCount - 1 To 0 Step -1
If dgvQuote.Rows(i).Cells(0).Value.ToString = "Step" Then
dgvQuote.Rows.RemoveAt(i)
End If
Next
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
My impatience, as well as a refocus, provided me with the answer.
My focus was always on the DataGridView and the feedback from it with regards to the number of rows contained in the control.
However, the execution of a loop took a snapshot of the number of rows at the start of the loop execution and did NOT update the number of rows every time rows were added to the DataGridView.
I took a different approach where I compared my current loop number (i += 1) with the current number of rows in the DataGridView (dgv.Rows.Count - 1) thereby forcing a recheck on the number of rows. This means that any new rows added to the DataGridView will now be counted in.
I added a trigger (True/False) to be set to true if the last row in the DataGridView was reach and the While...End While loop was exited.
'Show / Hide Route Step Data
Private Sub chkShowRouteStep_CheckedChanged(sender As Object, e As EventArgs) Handles chkShowRouteStep.CheckedChanged
Try
Dim lastRow As Boolean = False 'This will get set when we have reached the last row in the DGV
Dim i As Integer = 0
If chkShowRouteStep.Checked Then
'Show Route Steps
While lastRow <> True
txtRowCount.Text = i
If dgvQuote.Rows(i).Cells(0).Value.ToString <> "" Then
For j As Integer = 1 To 2
'i += 1
dgvQuote.Rows.Insert(i + j, "", "Step")
Next
End If
'Check to see if we have reached the last row, set lastRow to TRUE if it is the last row
If i = dgvQuote.Rows.Count - 1 Then
lastRow = True
End If
i += 1
End While
Else
'Hide Route Steps - WORKS GREAT
For x As Integer = dgvQuote.RowCount - 1 To 0 Step -1
If dgvQuote.Rows(x).Cells(1).Value.ToString = "Step" Then
dgvQuote.Rows.RemoveAt(x)
End If
Next
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
The result is as follows and error free:
Before
After
Since the comment in the code says you want to hide route steps, why not do just that? Instead of removing and inserting rows, populate the grid with everything and then use the checkbox to set the rows .Visible property?

How to remove a row from DataGridView if data within Total column is Zero

Hello Everyone Good Afternoon
I have a program that imports excel into datagridview but when after I import it the look is like this.
Link of the Image
as what you see in the image above I have a Column Total which composed of NULL(Empty String),0 and a certain data.
I wonder how can I delete the whole row if the column Total has a Data of NULL or 0.
Im using this code and it applies in Datagridview
Private Sub step_3_delete_Zero()
Dim SkipRemove As Boolean
Dim Rowindex As Integer
For Rowindex = DataGridView1.Rows.Count - 1 To 0 Step -1
SkipRemove = False
For Each Cell As DataGridViewCell In DataGridView1.Rows(Rowindex).Cells
If Not Cell.Value.ToString = "0" Then
SkipRemove = True
Exit For
End If
Next
If Not SkipRemove = False Then
DataGridView1.Rows.RemoveAt(Rowindex)
End If
Next
End Sub
I hope someone helps me, TY in advance
In your for each loop where have you said to look in the total cell?
Are you looking in every cell in that row?
Also isn't If SkipRemove = True Then easier to read than If Not SkipRemove = False Then?
I think it's not working because you are looping through and checking each cell rather than looping through by row and then checking the specific cell on each row.
Would something along the lines of this be more easier?
For Each row As DataGridViewRow In DataGridView1.Rows
If row.Cells.Item("Total").Value = "0" Then
DataGridView1.Rows.Remove(row)
End If
Next

Show only checked boxes in DataGridView

I am returning SQL results into a DataGridView and have run into a problem. I have an option on my form to only show checked values but can't get it working. Here's my code:
For x As Integer = dgvAutogrow.Rows.Count - 1 To dgvAutogrow.Rows.Count
If dgvAutogrow.Rows(x).Cells("checked").Value = False Then
dgvAutogrow.Rows.Remove(dgvAutogrow.Rows(x))
End If
Next
Here's what part of my DataGridView looks like. I want an event to occur that shows only values that have the check box checked.
When I debug I get the following error:
Any suggestions on what to change?
You have to cast the cell as DataGridViewCheckBoxCell and then test the value like this:
For x As Integer = dgvAutogrow.Rows.Count - 1 To 0 Step -1
Dim cel as DataGridViewCheckBoxCell
cel = CType(dgvAutogrow.Rows(x).Cells("YourColumnName"), DataGridViewCheckBoxCell)
If cel.Value = False Then
dgvAutogrow.Rows.Remove(dgvAutogrow.Rows(x))
End If
Next
Also, you had an ArgumentException because the column you specified doesn´t exist, you need to change that.
Code is tried and tested.
You can try this. We need to cast the cell as a DataGridViewCheckBoxCelland change your loop...
For x As Integer = dgvAutogrow.Rows.Count - 1 To 0 Step -1
If CType(dgvAutogrow.Rows(x).Cells("checked"), DataGridViewCheckBoxCell).Value = False Then
dgvAutogrow.Rows.Remove(dgvAutogrow.Rows(x))
End If
Next