How to get the ID of the most recently inserted Access record? [duplicate] - sql

I have the following set of code for a Sub program. It's inserting a row into a MSAccess Database using data provided in the containing form. What I would like to do is grab the ID number of this added record so that it can be set for a property of a window that is invoked when successfully added. I tried looking this up but I get something about ##IDENTITY but it's using an entirely different way of connecting.
Private Sub CreateTournament_Click(sender As System.Object, e As System.EventArgs) Handles CreateTournament.Click
' TODO: Check the form for errors, or blank values.
' Create the tournament in the database, add the values where needed. Close the form when done.
Dim cn As OleDbConnection
Dim cmd As OleDbCommand
Dim dr As OleDbDataReader
Dim icount As Integer
Dim str As String
Try
cn = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source='C:\Master.mdb'")
cn.Open()
str = "insert into Tournaments (SanctioningID,TournamentName,TournamentVenue,TournamentDateTime,TournamentFirstTable,Game,Format,OrganizerID) values(" _
& CInt(SanctioningIDTxt.Text) & ",'" & Trim(TournamentNameTxt.Text) & "','" & _
"1" & "','" & EventDateTimePck.Value & "','" & TableFirstNumberNo.Value & "','" & GameList.SelectedIndex & "','" & FormatList.SelectedIndex & "','" & Convert.ToInt32(ToIDTxt.Text) & "')"
'string stores the command and CInt is used to convert number to string
cmd = New OleDbCommand(Str, cn)
icount = cmd.ExecuteNonQuery
MessageBox.Show(icount)
'displays number of records inserted
Catch ex As Exception
MessageBox.Show(ex.ToString)
End Try
Me.Close()
Dim n As New TournamentWindow ' Open a new Tournament window if everything is successful
n.TournID = Counter '<< This should be set to the ID of the most recently inserted row
n.Show(HomeForm)'Invoke the form and assign "HomeForm" as it's parent.
End Sub

Assuming you have an auto increment column in the Tournaments table, you can do a "SELECT ##IDENTITY" to get the id of the last inserted record.
BTW, is the SanctioningIDTxt.Text unique? If so, can't you use that?

Related

My Code inserts only first row data in sqldatabase

How do I insert data of second row in SQL Server database? Here is my code:
Private Sub InsertStockDatagrid()
con.Open()
Dim cmdsrl As New SqlCommand("Select Code, Qty, Rate, Amt, Taxable, cgstamt, sgstamt,Type,Prefix,Srl,Branch FROM stock", con)
cmdsrl.Parameters.AddWithValue("Type", ComboBoxTranType.SelectedItem.ToString())
cmdsrl.Parameters.AddWithValue("Prefix", Lblprefix.Text)
cmdsrl.Parameters.AddWithValue("srl", TextINVNo.Text)
cmdsrl.Parameters.AddWithValue("Branch", LBLBranchcode.Text)
Dr8 = cmdsrl.ExecuteReader()
If (Dr8.Read()) Then
MessageBox.Show(" Unique field checked")
dr.Close()
Else
For Each Rw As DataGridViewRow In DataGridView1.Rows
'For RW As Integer = 0 To DataGridView1.Rows.Count - 1
Dim cmd = New SqlCommand("Insert into Stock (Code, Qty, Rate, Amt, Taxable, cgstamt, sgstamt,Type,Prefix,Srl,Branch) values('" & Rw.Cells(15).Value.ToString() & "','" & Rw.Cells(6).Value.ToString() & "','" & Rw.Cells(7).Value.ToString() & "','" & Rw.Cells(13).Value.ToString() & "','" & Rw.Cells(13).Value.ToString() & "','" & Rw.Cells(11).Value.ToString() & "','" & Rw.Cells(12).Value.ToString() & "','" & ComboBoxTranType.Text & "','" & Lblprefix.Text & "','" & TextINVNo.Text & "','" & LBLBranchcode.Text & "')", con)
cmd.ExecuteNonQuery()
Next
MessageBox.Show("Stock Data Entered")
con.Close()
Updatestocksrl()
End If
End Sub
Don't loop through the rows of DataGridView at all. Create a DataTable with the appropriate schema, populate it with initial data if appropriate and then bind it to the grid via a BindingSource. When it comes time to save the data, call Update on a SqlDataAdapter - the same one you used to retrieve the data if you did actually retrieve data - to save the changes from the DataTable. In its simplest form, that might look like this:
Private table As New Datatable
Private adapter As New SqlDataAdapter("SELECT * FROM MyTable", "connection string here")
Private commands As New SqlCommandBuilder(adapter)
Private Sub GetData()
adapter.Fill(table)
BindingSource1.DataSource = table
DataGridView1.DataSource = BindingSource1
End Sub
Private Sub SaveData()
Validate()
BindingSource1.EndEdit()
adapter.Update(table)
End Sub

object reference not set to an instance of the object Error when adding data into my database

I am having a problem when i am trying to put this data into my database
I'm using Vstudio 2013 and MS Access as my database
my problem is everytime i click add to add the data in my database this error always popping object reference not set to an instance of the object. even i declared the
Here's my Add button Code
Dim cn As OleDb.OleDbConnection
Dim cmd As OleDb.OleDbCommand
Private Sub btnAdd_Click(sender As Object, e As EventArgs) Handles btnAdd.Click
Try
If cn.State = ConnectionState.Open Then
cn.Close()
End If
cn.Open()
cmd.Connection = cn
cmd.CommandText = "INSERT INTO gradess ( StudentNo,StudentName,StudentSection,SubjectNo1,SubjectNo2,SubjectNo3,SubjectNo4,SubjectNo5,SubjectNo6,SubjectNo7,SubjectNo8,TotalAverage) " & "Values('" & txtStudentNo.Text & "','" & lblName.Text & "','" & lblSection.Text & "','" & txtSubject1.Text & "','" & txtSubject2.Text & "','" & txtSubject3.Text & "','" & txtSubject4.Text & "','" & txtSubject5.Text & "','" & txtSubject6.Text & "','" & txtSubject7.Text & "','" & txtSubject8.Text & "','" & lblTotalAverage.Text & "')"
cmd.ExecuteNonQuery()
refreshlist()
disablebutton()
MsgBox("Successfully Added!!", vbInformation, "Successful")
clear()
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
When you declare a variable like Dim cn As OleDb.OleDbConnection you are just telling the compiler what type it is not creating an object of that type.
When you use the New keyword OleDb.OleDbConnection is not just the name of a class (the data type) but it is an actual method. It is calling the constructor of the class which returns an instance of the object.
In C# you are required to put the parenthesis after like OleDb.OleDbConnection() which shows you are calling a method. You can add the parenthesis in vb.net but it is not required but I think it is a good reminder of the difference between setting a data type and creating an object.
Your declaration should be : Dim cn As New OleDb.OleDbConnection Dim cmd As New OleDb.OleDbCommand
– F0r3v3r-A-N00b 20 mins ago

Copying from one Datagridview to another Leading Zero disappear

Basically i have 2 dgv, dgv1 is the list(PLU, Desc) and dgv2 is empty with the ff columns (PLU,Desc,Qty). also both dgv is connected to access 2007 table
in the textbox you enter the PLU then the 1st dgv display it. then if you press it will add it to the 2nd datadrigview with a qty=1,
the problem is when every it copies the PLU from dgv1 the leading zero disappear in dgv2.
Search in 1st dgv(on text change)
connect()
Dim dt As New DataTable
Dim da As New OleDbDataAdapter("SELECT * FROM Data WHERE PLU_SKU = '" & TextBox1.Text & "'", connection)
da.Fill(dt)
DataGridView1.DataSource = dt
connection.Close()
da.Dispose()
then (on keypress) it save to 2nd dgv
connect()
Dim cmd
Dim q As Integer
q = 1
If e.KeyCode = Keys.Enter Then
For Each rw As DataGridViewRow In DataGridView1.Rows
MessageBox.Show(rw.Cells(0).Value)
DataGridView2.Columns("PLU_SKU").DefaultCellStyle.Format = "D9"
cmd = New OleDbCommand("insert into NEW (PLU_SKU,Description,QTY) values (" & rw.Cells(0).Value & ",'" & rw.Cells(1).Value & "','" & q & "') ", connection)
cmd.ExecuteNonQuery()
Next
connection.Close()
MessageBox.Show("Saved")
End If
showData1()
as you can see i have a messagebox that show me the value of "rw.Cells(0).Value"
and the value is correct. but still i instead of 022 it becomes 22.
now im at a loss on where the problem.
I tried to apply what was said in Leading zero in DataGridView
but problem is still there.
any help? thank you.
Nevermind, Found my problem seems i forgot the ' in the " & rw.Cells(0).Value & ".
it was supposed to be '" " & rw.Cells(0).Value & "'. thanks anyways.

Refreshing a data grid view

This looks like an easy fix but I can't figure this out. I'm trying to have button click event on a subForm (NewTournament), add a record to a database, and then to notify a data grid which lists the records from the same database automatically (the grid is listed on HomeForm).
I so for am able to update the database and call upon a new window. But I can't get it to refresh that datagrid for anything. I know I'm supposed to clear the datagrid, get changes, then refill the grid. But everytime I do this, the code is NOT updating. Furthermore, I can very well see that the record is being added.
Private Sub CreateTournament_Click(sender As System.Object, e As System.EventArgs) Handles CreateTournament.Click
' Check the form for errors, if none exist.
' Create the tournament in the database, add the values where needed. Close the form when done.
Dim cn As OleDbConnection
Dim cmd, cmd1 As OleDbCommand
Dim icount As Integer
Dim str, str1 As String
Try
cn = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source='C:\Users\Paul Williams III\Documents\Visual Studio 2010\Projects\Everything OP Client\Everything OP Client\Master.mdb'")
cn.Open()
str = "insert into Tournaments (SanctioningID,TournamentName,TournamentVenue,TournamentDateTime,TournamentFirstTable,Game,Format,OrganizerID) values(" _
& CInt(SanctioningIDTxt.Text) & ",'" & Trim(TournamentNameTxt.Text) & "','" & _
"1" & "','" & EventDateTimePck.Value & "','" & TableFirstNumberNo.Value & "','" & GameList.SelectedIndex & "','" & FormatList.SelectedIndex & "','" & Convert.ToInt32(ToIDTxt.Text) & "')"
'string stores the command and CInt is used to convert number to string
cmd = New OleDbCommand(str, cn)
str1 = "select ##Identity"
icount = cmd.ExecuteNonQuery
cmd1 = New OleDbCommand(str1, cn)
Counter = CInt(cmd1.ExecuteScalar)
MessageBox.Show(Counter & " was the last inserted id")
'displays number of records inserted
HomeForm.MasterDataSet.Clear()
HomeForm.MasterDataSet.GetChanges()
HomeForm.TournamentsTableAdapter.Fill(HomeForm.MasterDataSet.Tournaments)
HomeForm.DataGridView1.Refresh()
Catch ex As Exception
MessageBox.Show(ex.ToString)
End Try
Me.Close()
Dim n As New TournamentWindow
n.TournID = Counter
n.Show(HomeForm)
End Sub
The best approach is to add the record to the DataSource of the DataGrid. The DataGrid will automatically update. In this case its likely to be somehting like
HomeForm.MasterDataSet.Tournaments.AddTournamentsRow( CInt(SanctioningIDTxt.Text) , _
Trim(TournamentNameTxt.Text) , _
"1" , _
EventDateTimePck.Value, _
TableFirstNumberNo.Value, _
GameList.SelectedIndex, _
FormatList.SelectedIndex, _
Convert.ToInt32(ToIDTxt.Text) )
As an aside you might want to consider using parameterized queries for your Insert statement
This is my answer I hope you like it. On my project I have a switchboard and in that switchboard it contains the data grid view for my data. Before it only refresh it self when the user used the query and it will refresh it self. I taught about it how to do it different. So I used this technique the timer refresh effect. How does it work I put a timer and in the timer I copy and paste this code from the form load.
Me.ADDRESS_TICKETTableAdapter.Fill(Me.Database1DataSet.ADDRESS_TICKET)
And in the settings of the timer i turn it on and every 9 seconds it reloads the data you can change it that it reloads every 1 second if you like depends how many records it comes in. I hope this answer help you in anyway. It work for me.

Multiple if statements, then, or else?

I'm having some problems getting a query to run based off another query. Here's the database diagram to give a little background. The primary keys for all the tables are automatically generated by identites. The first 2 insert statements (Donation and Food_Donation) work but I can't get the last insert into Donation_Details to work. Here's the code so far:
Dim con As New OleDbConnection(DBcon)
Try
Dim dr As OleDbDataReader
Dim command As New OleDbCommand("Insert into Donation (Donor_ID) VALUES ( " & txtDonNum.Text & "); Select ##Identity;")
con.Open()
command.Connection = con
dr = command.ExecuteReader
Dim Donation_ID As String = ""
If dr.Read() Then
Donation_ID = dr(0).ToString
Dim food As New OleDbCommand("Insert into Food_Donation (Date_Received, Donation_ID) Values ( '" & maskedreceived.Text & "', " & Donation_ID & "); Select ##Identity")
food.Connection = con
food.ExecuteNonQuery()
End If
Dim Food_ID As String = ""
If dr.Read() Then
Food_ID = dr(0).ToString
Dim food2 As New OleDbCommand("Insert into Donation_Details (Quantity, Unit, Expiration_Date, Food_ID, Storage_ID, Type_ID) Values ( " & txtQuantity.Text & ", '" & boxUnit.Text & "', '" & maskedexpire.Text & "', " & Food_ID & ", " & txtStorageID.Text & ", " & txtTypeID.Text & ")")
food2.Connection = con
food2.ExecuteNonQuery()
End If
Catch ex As Exception
MessageBox.Show(ex.Message)
Finally
con.Close()
End Try
End sub
I'm fairly correct my SQL statements are correct and it's just whether or not the last statements need to be an If or something else.
You should be using dr = food.ExecuteReader() rather than food.ExecuteNonQuery() if you want to reuse dr to acquire Food_ID?
I suspect your problem is that you're using If dr.Read() twice.
The dr.Read() method will move the reader forward to the next row but you are only selecting a single value in your initial query.
So, for example, your reader (being made from the insert) will return a single row value for the successful insert. Calling Read() on it will succeed but then move the row cursor to EOF causing subsequent Read() calls to return FALSE