So I have a DataGridView filled with data with the Primary Key being ex."Order Number". Whenever a new row is added to the DGV, I have this line of code added to target the new row.
dgv.Rows(dgv.Rows.Count - 1).Selected = True
This works great and all, but whenever a user is sorted on a column header, this will go to the last row like it is supposed to do, but that's not where the new row is.
So is it possible for me to do this, but to target the highest primary key number? Since the newest row being added will contain the highest primary key number at the time of creation.
Thank you.
UPDATE: I have found a way to get the highest value of such primary key by using:
Dim MaxID = dgv.Rows.Cast(Of DataGridViewRow)().Max(Function(r) Convert.ToInt32(r.Cells("Order Number").Value))
But whenever I use:
dgv.Rows(MaxID).Selected = True
I get an error saying the value is outside the bounds of the array. I tried MaxID - 1 as well.
One way to get there:
Dim qry = (From r As DataGridViewRow In Me.dgv1.Rows
Order By r.Cells("Order Number").Value Descending
Select r.Index)
If qry.Any Then
Dim idx As Integer = qry.First
Me.dgv1.Rows(idx).Selected = True
End If
Or you can directly select the row
Dim targetRow = Me.dgv1.Rows.Cast(Of DataGridViewRow)().
OrderByDescending(Function(r) r.Cells("Order Number").Value).FirstOrDefault
If targetRow IsNot Nothing Then targetRow.Selected = True
The way that I had to resort to doing is by resetting the sort from the DataSet that was filling the DataGridView, and then select the row and currentcell.
DataSet.Tables("TableName").DefaultView.Sort = ""
dgv.Rows(dgv.Rows.Count - 1).Selected = True
dgv.CurrentCell = dgv.Rows(dgv.Rows.Count - 1).Cells(dgv.FirstDisplayedCell.ColumnIndex)
Definitely not the best fix, because I am resetting the sort before focusing on a row, but it will hold the users over for the time being.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.