Target Highest Primary Key When Adding New Row to DataGridView - vb.net

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.

Related

Whats the alternative efficient method to retrieve the row index from data grid view with over 7000 + record in vb.net?

This is my current method. It's working right now but it is very inefficient. Can someone help me with an alternative to this?
P.S. Not the selected index. I am going to search for the recordID and then retrieve the row index of this recordID (tempProxyID) below.
For Each row As DataGridViewRow In dgv.Rows
Dim temp As String = row.Cells.Item(0).Value
If temp.ToString.Trim = tempProxID Then
rowindex = Convert.ToInt32(row.Index.ToString())
End If
Next

Compare DataTable and DataGridView and hightlight matching rows in DataGridView

I have a database table which contains a list of usernames and their current active location, an integer called SEQUENCE.
I get this list of sequence numbers into a datatable with a single column (e.g. "SELECT SEQUENCE FROM TABLE"):
dtUsers = CLS_USERS.GetUsers(User)
It excludes the current user, which is why I parse in User.
What I then do is loop through the datatable and for each number I want to set the matching row in a datagridview (which also has a SEQUENCE column) to a different colour. This is my current code:
For Each row As DataRow In dtUsers.Rows
intSeq = row("SEQUENCE")
For Each dgv_row As DataGridViewRow In dgvCandList.Rows
If dgv_row.Cells("CURRENT_SQ").Value = intSeq Then
dgv_row.DefaultCellStyle.BackColor = Color.Cyan
Else
dgv_row.DefaultCellStyle.BackColor = Color.Grey
End If
Next
Next
However, all rows are highlighted rather than just those where dgv_row.Cells("SV_CURRENT_CAND_SQ").Value = intSeq is True... I've verified that this loop is working correctly, so it must be dgv_row.DefaultCellStyle.BackColor = Color.Cyan which is incorrect?
If so, how should I correctly be assigning the row back colour of specific DataGridRow?
EDIT: This code works correctly, my issue was related to bug outside this loop causing the BackColor to be sent for everything, and then never setback to default if where BackColor wasn't being set back to the default if it wasn't in dtUsers.

Clear all the value of a datagridview column once in vb.net

i have user below code to clear the cell value of a datagridview column.
For Each item As DataGridViewRow In dgvGeometricImport.Rows
item.Cells("Status1").Value = String.Empty
Next
Do we have any short cut to clear all value without iterating the rows?
can we use linq to achieve this?
thanks in advance
With or without a DataSource set, you can *remove and re-add the column.
VB Example with DataSource set:
Dim index As Integer = Me.dataGridView1.Columns("Status1").DisplayIndex
Dim table As DataTable = DirectCast(Me.dataGridView1.DataSource, DataTable)
Dim column As DataColumn = table.Columns("Status1")
table.Columns.Remove(column)
table.Columns.Add(column)
Me.dataGridView1.Columns("Status1").DisplayIndex = index
VB Example without DataSource set:
Dim index As Integer = Me.dataGridView1.Columns("Status1").Index
Dim column As DataGridViewColumn = Me.dataGridView1.Columns("Status1")
Me.dataGridView1.Columns.Remove(column)
Me.dataGridView1.Columns.Insert(index, column)
*Disclaimer: This will work, but if I'm being honest I can't say for certain that there's no iteration occurring at some lower level. After all, when you re-add the column it becomes a part of each row entry and therefore could have been iterated through under-the-hood.
One approach would be to use jQuery selectors. It would of course still iterate through the rows, but it would be done client side and behind the scene.
$('#' + gridViewCtlId + ' td:nth-child(' + INDEX_COLUMN_TO_CLEAR + ')').html('');
use this :
dataGridView.Rows.Cast(Of DataGridViewRow).ToList.ForEach(Sub(r) r.Cells("ColumnName").Value = String.Empty)
but it's the same thing, linq will do the iteration

How to search in and edit Table by using DataGridView

I have a SQL database with a table "Employees" in it (with large number of rows). By using DataGridView, I want to search for specific "Employee's Name" and change it's "Job". How can I achieve that. I'm using VB.net. Please Help Me.
Not sure if this will help but write a loop that goes through all the values if it finds a match its true if not it is false ,if found the item can be displayed in a textbox and edited
if not a message is displayed saying "no match found"
the editing part can be done using a procedure that will update the value in your grid with what is entered
i can supply code for this if need be but i am unsure if this is what you wish
and there is most likely a better way of doing it
you can loop through your grid, and check if the data you wish to edit exists using the For loop:
Supposing you are using a textbox as the input, and you use a label to hold the employee ID:
Dim EmpIDColumn as Integer = 'array number of your EmpID Column
Dim EmpNameColumn as Integer = 'The array number of the column where your EmpName is
Dim JobColumn as Integer = 'The array number of your job column
For each dr as Datagridviewrow in Datagridview1.Rows
If dr.cells(EmpNameColumn).value = TxtSearchBox.text Then
txtEmpJob.text = dr.cells(JobColumn).value
lblEmpID.Text = dr.cells(EmpIDColumn).value
End if
Next
Okay, so you've searched the record successfully. Next step (after editing the job, and even other details like the name) would be to update the record in the grid. Remember you set the lblEmpID's text to empID in the column? Use it to find the
Record you wish to change in the grid using the same technique above!
Dim EmpIDColumn as Integer = 'array number of your EmpID Column
Dim EmpNameColumn as Integer = 'The array number of the column where your EmpName is
Dim JobColumn as Integer = 'The array number of your job column
For each dr as Datagridviewrow in Datagridview1.Rows
If dr.cells(EmpIDColumn).value = lblEmpID.text Then
dr.cells(JobColumn).value = txtEmpJob.text
dr.cells(EmpNameColumn).value = txtEmpName.text
'then, type in here your SQL Query Update!
End if
Next

How can I update a row in a DataTable in VB.NET?

I have the following code:
Dim i As Integer = dtResult.Rows.Count
For i = 0 To dtResult.Rows.Count Step 1
strVerse = blHelper.Highlight(dtResult.Rows(i).ToString, s)
' syntax error here
dtResult.Rows(i) = strVerse
Next
I want to add a strVerse to the current row.
What am I doing wrong?
The problem you're running into is that you're trying to replace an entire row object. That is not allowed by the DataTable API. Instead you have to update the values in the columns of a row object. Or add a new row to the collection.
To update the column of a particular row you can access it by name or index. For instance you could write the following code to update the column "Foo" to be the value strVerse
dtResult.Rows(i)("Foo") = strVerse
You can access columns by index, by name and some other ways:
dtResult.Rows(i)("columnName") = strVerse
You should probably make sure your DataTable has some columns first...
Dim myRow() As Data.DataRow
myRow = dt.Select("MyColumnName = 'SomeColumnTitle'")
myRow(0)("SomeOtherColumnTitle") = strValue
Code above instantiates a DataRow. Where "dt" is a DataTable, you get a row by selecting any column (I know, sounds backwards). Then you can then set the value of whatever row you want (I chose the first row, or "myRow(0)"), for whatever column you want.