Reputation: 209
How to select the last record which is added or updated in datagridview This is how i add
Insert into table (Name, AddDate) values ('" & Name & "', '" & Date.Now & "')"
After adding the record i refresh dgv
("Select * from table")
Form1.DGV.DataSource = SQLDataset1.Tables(0)
And this is how i update record
("Update table Set Name='" & txtT.Text & "' , DateEdit='" & Date.Now & "' Where Town= '" & txtT.Text & "'")
Edit :
Public Sub addIt(Name As String)
Try
Dim addStr As String = "Insert into tableName (Name, AddDate) values ('" & Name & "', '" & Date.Now & "')"
sqlcon.Open()
SqlCom = New SqlCommand(addStr, sqlcon)
SqlCom.ExecuteNonQuery()
sqlcon.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
'Buton click event
If Len(town) >= 3 Then
sql.addIt(town)
Msgbox("Added")
sql.resetDGV()
End If
Public Sub resetDGV()
sqlquery("Select * from tableName")
Form1.dgv.DataSource = SQLDataset.Tables(0)
End Sub
Upvotes: 0
Views: 826
Reputation: 550
There are easier ways outside in the www. But this is the shortest so....
Public Sub addIt(Name As String) as int
Dim insertedID as int = -1
Try
Dim addStr As String = "Insert into tableName (Name, AddDate) OUTPUT INSERTED.ID values ('" & Name & "', '" & Date.Now & "')"
sqlcon.Open()
SqlCom = New SqlCommand(addStr, sqlcon)
returnValue = Convert.ToInt32(SqlCom.ExecuteScalar())
sqlcon.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
return insertedID
End Sub
If Len(town) >= 3 Then
Dim insertedID as int = sql.addIt(town)
If insertedID = -1 Then return
Msgbox("Added")
sql.resetDGV()
'Select
SelectLastInsertedRow(insertedID)
End If
Public Sub resetDGV()
sqlquery("Select * from tableName")
Form1.dgv.DataSource = SQLDataset.Tables(0)
End Sub
Private Sub SelectLastInsertedRow(id as int)
For Each row as DataGridViewRow in dgv.Rows
'Check if row belongs to the ID
if(row == id) Then
'Select
row.Select = true
End if
End For
End Sub
This code is not tested. But it should work :P
Upvotes: 1