Cant insert data in database (Access) VB.NET - database

Im working on a project. Our system is Hotel Reservation. In VB it says that it added in my database
but then when I check my database there is none.
What is the problem
btw Here's the code:
Public Class RegistrationForm
Private Sub btnNext_Click(sender As Object, e As EventArgs) Handles btnNext.Click
qry = "INSERT INTO tblGuest(GuestName, Gender, Address)VALUES('" &
txtName.Text & "','" &
txtGender.Text & "','" &
txtAddress.Text & "');"
cmd = New OleDb.OleDbCommand(qry, con)
dr = cmd.ExecuteReader()
MsgBox("Succesfully added in database")
RoomInfoForm.Show()
End Sub
Private Sub RegistrationForm_Load(sender As Object, e As EventArgs) Handles MyBase.Load
koneksyon()
End Sub
End Class

Just because your MsgBox fires doesn't mean the query did what you expect.
This is more like what you want to do:
Private Sub btnNext_Click(sender As Object, e As EventArgs) Handles btnNext.Click
'parameterize the query to avoid SQL injection attacks which is the #1 code vulnerability on OWASP Top 10
Dim qry As String = "INSERT INTO tblGuest(GuestName, Gender, Address)VALUES(?, ?, ?);"
'Put disposable resources within Using blocks
Using con As New OleDb.OleDbConnection()
Using cmd As New OleDb.OleDbCommand(qry, con)
'Create the parameters.
Dim paramName As New OleDb.OleDbParameter("#p1", OleDb.OleDbType.VarChar)
paramName.Value = txtName.Text 'you should null check and validate all these textbox values
Dim paramGender As New OleDb.OleDbParameter("#p2", OleDb.OleDbType.VarChar)
paramGender.Value = txtGender.Text
Dim paramAddress As New OleDb.OleDbParameter("#p3", OleDb.OleDbType.VarChar)
paramAddress.Value = txtAddress.Text
'Assign the parameters to the command
cmd.Parameters.Add(paramName)
cmd.Parameters.Add(paramGender)
cmd.Parameters.Add(paramAddress)
'you are not returning a result set from the command, so ExecuteNonQuery
cmd.ExecuteNonQuery()
End Using
End Using
MsgBox("Succesfully added in database")
RoomInfoForm.Show()
End Sub

Related

“Not allowed to change the 'ConnectionString' property.” error

While i was adding data to access database, i got error:
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
TB2.Clear()
NameofG.Clear()
NunberofG.Clear()
UnitofG.Clear()
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
pro = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Piyawat\Desktop\PPCC\Stock.accdb;"
connstring = pro
myconnection.ConnectionString = connstring
If myconnection.State = ConnectionState.Closed Then
myconnection.Open()
End If
command = "insert into Stock([InvoiceID],[Type],[Item],[Amout],[Unit]) Value ('" & TB2.Text & "','" & CB1.Text & "','" & NameofG.Text & "','" & NunberofG.Text & "','" & UnitofG.Text & "')"
Dim cmd As OleDbCommand = New OleDbCommand(command, myconnection)
cmd.Parameters.Add(New OleDbParameter("InvoiceID", CType(TB2.Text, String)))
cmd.Parameters.Add(New OleDbParameter("Type", CType(CB1.Text, String)))
cmd.Parameters.Add(New OleDbParameter("Item", CType(NameofG.Text, String)))
cmd.Parameters.Add(New OleDbParameter("Amout", CType(NunberofG.Text, String)))
cmd.Parameters.Add(New OleDbParameter("Unit", CType(UnitofG.Text, String)))
MsgBox("Record Save")
Try
cmd.ExecuteNonQuery()
cmd.Dispose()
TB2.Clear()
CB1.Text.DefaultIfEmpty
NameofG.Clear()
NunberofG.Clear()
UnitofG.Clear()
Catch ex As Exception
MsgBox("Mistake")
End Try
End Sub
How to fix the error? Please help. Thanks
I would AWAYS ensure that after you use the connection, you close it.
however, you can get .net to automatics do this for you.
Also, go into project->settings and add your connection string there - that way you NEVER have to place or have connection strings in code - (bad idea).
Hence, your code should and would look like this:
Dim strSQL As String = "INSERT INTO Stock([InvoiceID],[Type],[Item],[Amout],[Unit]) " &
"VALUES (#TB2, #CB1, #NameofG, #NunberofG, #UnitofG)"
Using cmd As New OleDbCommand(strSQL, New OleDbConnection(My.Settings.Test44))
cmd.Parameters.Add("#TB2", OleDbType.VarWChar).Value = TB2.Text
cmd.Parameters.Add("#CB1", OleDbType.VarWChar).Value = CB1.Text
cmd.Parameters.Add("NameofG", OleDbType.VarWChar).Value = NameofG.Text
cmd.Parameters.Add("#NumberofG", OleDbType.Integer).Value = NunberofG.Text
cmd.Parameters.Add("#UnitofG", OleDbType.Integer).Value = UnitOfG.Text
cmd.Connection.Open()
Try
cmd.ExecuteNonQuery()
MsgBox("Record Save")
Catch ex As Exception
MsgBox("Error = " & ex.Message)
End Try
End Using
note the following:
No messy string concentation.
No messy quotes for strings, non quotes for numbers.
clean easy to read.
use parmaters - safe.
And with a using block, we do NOT have to dispose or close the conneciton - it is automatic for you. So ALWAYS assume it is closed.
note how we don't have a seperate conneciton object - don't need one.
note how the command object is REALLY nice.
The command object has:
a connection object - you don't need to create a new one
command text
a reader!!! - you can use command object - no need to load + create a reader
I moved the database code to a separate method.
Starting with the user interface code, you first want to validate the input. I had to guess at the datatypes because your code made them all look like strings. I hope this is not true.
It seems you got mixed up with Parameters. I am very glad that you tried to used them but they don't appear in your sql string so they are not being used. You don't want to concatenate strings with user input because it risks sql injection.
The # sign preceding the parameter names is just a convention that makes it easy to recognize.
You need to keep database objects local to the method where they are used. That way they can be closed and disposed with Using...End Using blocks as quickly as possible.
Private ConStr As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Piyawat\Desktop\PPCC\Stock.accdb;" '"Your connection string"
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
'Validate input
Dim ID As Integer
Dim Amt As Decimal
Dim Unt As Integer
Dim message = "Please enter a number for the"
If Not Integer.TryParse(TB2.Text, ID) Then
MessageBox.Show(message & " Invoice ID.")
Return
End If
If Not Decimal.TryParse(NunberofG.Text, Amt) Then
MessageBox.Show(message & " Amount.")
Return
End If
If Not Integer.TryParse(UnitofG.Text, Unt) Then
MessageBox.Show(message & " Unit")
Return
End If
'Call the insert method
Try
InsertInvoice(ID, CB1.Text, NameofG.Text, Amt, )
Catch ex As Exception
MsgBox(ex.Message)
Return
End Try
MessageBox.Show("Record Saved")
TB2.Clear()
CB1.Text.DefaultIfEmpty
NameofG.Clear()
NunberofG.Clear()
UnitofG.Clear()
End Sub
Private Sub InsertInvoice(InvoiceID As Integer, Type As String, Item As String, Amount As Decimal, Unit As Integer)
Dim Command = "insert into Stock([InvoiceID],[Type],[Item],[Amout],[Unit]) Value (#InvoiceID,#Type,#Item,#Amount,#Unit)"
Using myconnection As New OleDbConnection(ConStr),
cmd As New OleDbCommand(Command, myconnection)
With cmd.Parameters
.Add("#InvoiceID", OleDbType.Integer).Value = InvoiceID
.Add("#Type", OleDbType.VarChar).Value = Type
.Add("#Item", OleDbType.VarChar).Value = Item
.Add("#Amout", OleDbType.Decimal).Value = Amount
.Add("#Unit", OleDbType.Integer).Value = Unit
End With
End Using
End Sub

System.Data.SqlClient.SqlException: 'Incorrect syntax near '​'.'

I get this SQL Server error and I can't figure out where the trouble is:
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
xception Details: System.Data.SqlClient.SqlException: 'Incorrect syntax near '​'.'
Source Error: Line: 46
Error Line: cmdsql.ExecuteNonQuery()
Code:
Dim connexcel As OleDbConnection
Dim daexcel As OleDbDataAdapter
Dim dsexcel As DataSet
Dim cmdexcel As OleDbCommand
Dim drexcel As OleDbDataReader
Dim connsql As SqlConnection
Dim dasql As SqlDataAdapter
Dim dssql As DataSet
Dim cmdsql As SqlCommand
Dim drsql As SqlDataReader
Private Sub import_excel_to_sql_server_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Me.CenterToScreen()
End Sub
Private Sub BtnImpExcelFile_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnImpExcelFile.Click
On Error Resume Next
OpenFileDialog1.Filter = "(* .xls) | * .xls | (*. Xlsx) | *. xlsx | All files (*. *) | *. * "
OpenFileDialog1.ShowDialog()
FileAdd.Text = OpenFileDialog1.FileName
connexcel = New OleDbConnection("provider = Microsoft.ace.OLEDB.12.0; data source =" & FileAdd.Text & "; Extended Properties = Excel 8.0;")
connexcel.Open()
Dim dtSheets As DataTable = connexcel.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, Nothing)
Dim listSheet As New List(Of String)
Dim drSheet As DataRow
For Each drSheet In dtSheets.Rows
listSheet.Add(drSheet("TABLE_NAME").ToString())
Next
For Each sheet As String In listSheet
ExcelSheetList.Items.Add(sheet)
Next
End Sub
Private Sub ExcelSheetList_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ExcelSheetList.SelectedIndexChanged
daexcel = New OleDbDataAdapter("select * from [" & ExcelSheetList.Text & "]", connexcel)
dsexcel = New DataSet
daexcel.Fill(dsexcel)
DGVImpData.DataSource = dsexcel.Tables(0)
DGVImpData.ReadOnly = True
End Sub
Sub connections()
connsql = New SqlConnection("data source =. \ MSSMLBIZ; initial catalog = MyInvoice; integrated security = true")
connsql.Open()
End Sub
Private Sub BtnSaveImpData_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnSaveImpData.Click
For line As Integer = 0 To DGVImpData.RowCount - 2
Call connections()
Dim save As String = "insert into InvoiceData values ​​('" & DGVImpData.Rows(line).Cells(0).Value & "', '" & DGVImpData.Rows(line).Cells(1).Value & "')"
cmdsql = New SqlCommand(save, connsql)
cmdsql.ExecuteNonQuery()
Next
MsgBox("data saved successfully")
DGVImpData.Columns.Clear()
End Sub
Keep your database objects local so you can be sure they are closed and disposed. Enclosing these objects with `Using...End Using blocks will accomplish this even if there is an error. You don't need variables for DataAdapters, DataSets, or DataReaders. I suggest only one form level variable for the Excel connection string since it is used in 2 methods.
A little bit of Linq will get the retrieved sheet names from the DataTable and fill an array. The array can then be passed to the list box with .AddRange.
I wouldn't use the SelectedIndexChanged event because the user can too easily click the wrong sheet or change their mind. I used a Button.Click event to fill the grid.
The Sql connection string looks strange to me. I suggest you test it separately. If it doesn't work, this is a good resource. https://www.connectionstrings.com/
I would specifically state the column names in the Insert statement. Replace FirstColumnName and SecondColumnName with the real column names. The parameter names can be anything you wish as long as the names in the statement match the names in the Parameters.Add method. I have guessed at the datatypes and the size. Check your database for correct values.
We add the parameters only once outside the loop then change only values inside the loop.
Private ExcelConString As String
Private Sub BtnImpExcelFile_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnImpExcelFile.Click
Dim strFileName As String
Dim dtSheets As DataTable
OpenFileDialog1.Filter = "(* .xls) | * .xls | (*. Xlsx) | *. xlsx | All files (*. *) | *. * "
OpenFileDialog1.ShowDialog()
strFileName = OpenFileDialog1.FileName
ExcelConString = "provider = Microsoft.ace.OLEDB.12.0; data source =" & strFileName & "; Extended Properties = Excel 8.0;"
Using connexcel = New OleDbConnection(ExcelConString)
connexcel.Open()
dtSheets = connexcel.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, Nothing)
End Using
Dim exSheets() As Object = (From dRow In dtSheets.AsEnumerable() Select dRow("TABLE_Name")).ToArray
ExcelSheetList.Items.AddRange(exSheets)
End Sub
Private Sub DisplayData_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles DisplayData.Click
Dim dt As New DataTable
Using cn As New OleDbConnection(ExcelConString)
'In older versions of Visual Studio you may have to use String.Format instead of the interpolated string.
Using cmd As New OleDbCommand($"select * from [{ExcelSheetList.Text}];", cn)
cn.Open()
dt.Load(cmd.ExecuteReader)
End Using
End Using
DGVImpData.DataSource = dt
DGVImpData.ReadOnly = True
End Sub
Private Sub BtnSaveImpData_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnSaveImpData.Click
Using cn As New SqlConnection("data source =. \ MSSMLBIZ; initial catalog = MyInvoice; integrated security = true")
Using cmd As New SqlCommand("Insert Into InvoiceData (FirstColumnName, SecondColumnName) Values ​​(#FirstColumn, #SecondColumn);", cn)
cmd.Parameters.Add("#FirstColumn", SqlDbType.VarChar, 100)
cmd.Parameters.Add("#SecondColumn", SqlDbType.VarChar, 100)
cn.Open()
For line As Integer = 0 To DGVImpData.RowCount - 2
cmd.Parameters("#FirstColumn").Value = DGVImpData.Rows(line).Cells(0).Value
cmd.Parameters("#SecondColumn").Value = DGVImpData.Rows(line).Cells(1).Value
cmd.ExecuteNonQuery()
Next
End Using
End Using
MsgBox("data saved successfully")
DGVImpData.Columns.Clear()
End Sub
As to error handling... On Error Resume Next is generally not used in new code. We have Try...Catch...Finally blocks. After your code is running add these blocks where needed.
EDIT
To use String.Format...
Using cmd As New OleDbCommand(String.Format("select * from [{0}];", ExcelSheetList.Text))
The first parameter is the string in which you wish to place variables. It contains indexed placeholders enclosed in braces. The following parameters are the variables you want for the placeholder substitution.
Thank you for helping me to a fixed error in my code. Here is Final code without System.Data.SqlClient.SqlException: 'Incorrect syntax near '​'.' error.
Now I tried to improve code with the last section(mention below) to define parameters for exporting data. Because I have a large number of data for exporting to SQL Server I get a Timeout error. Can anyone be able to improve code for quick exporting data to SQL Server?
connsql.Open() "System.InvalidOperationException: 'Timeout expired. The timeout period elapsed prior to obtaining a connection from the pool. This may have occurred because all pooled connections were in use and max pool size was reached.'"
Dim connexcel As OleDbConnection
Dim daexcel As OleDbDataAdapter
Dim dsexcel As DataSet
Dim cmdexcel As OleDbCommand
Dim drexcel As OleDbDataReader
Dim connsql As SqlConnection
Dim dasql As SqlDataAdapter
Dim dssql As DataSet
Dim cmdsql As SqlCommand
Dim drsql As SqlDataReader
Private Sub Import_excel_to_sql_server_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Me.CenterToScreen()
End Sub
Private Sub PKGAbtnImpExcelFile_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles PKGAbtnImpExcelFile.Click
On Error Resume Next
'OpenFileDialog1.Filter = "(*.xls)|*.xls|(*.xlsx)|*.xlsx|All files (*.*)|*.*"
PKGAofdImpOpenExcel.ShowDialog()
PKGAtxtImpFileAdd.Text = PKGAofdImpOpenExcel.FileName
connexcel = New OleDbConnection("provider=Microsoft.ace.OLEDB.12.0;data source=" & PKGAtxtImpFileAdd.Text & ";Extended Properties=Excel 8.0;")
connexcel.Open()
Dim dtSheets As DataTable = connexcel.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, Nothing)
Dim listSheet As New List(Of String)
Dim drSheet As DataRow
For Each drSheet In dtSheets.Rows
listSheet.Add(drSheet("TABLE_NAME").ToString())
Next
For Each sheet As String In listSheet
PKGAtxtImpExlSheetL.Items.Add(sheet)
Next
End Sub
Private Sub PKGAtxtImpExlSheetL_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles PKGAtxtImpExlSheetL.SelectedIndexChanged
daexcel = New OleDbDataAdapter("select * from [" & PKGAtxtImpExlSheetL.Text & "]", connexcel)
dsexcel = New DataSet
daexcel.Fill(dsexcel)
PKGAdgvImpData.DataSource = dsexcel.Tables(0)
PKGAdgvImpData.ReadOnly = True
End Sub
'Last Section
Sub Connectonsql()
connsql = New SqlConnection("Data Source=DESKTOP-MIQGJTK\MSSMLBIZ;Initial Catalog=PkGlobalAccounting;Integrated Security=True")
connsql.Open()
End Sub
Private Sub PKGAbtnImpSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles PKGAbtnImpSave.Click
For Line As Integer = 0 To PKGAdgvImpData.RowCount - 2
Call Connectonsql()
Dim save As String = "insert into Test values('" & PKGAdgvImpData.Rows(Line).Cells(0).Value & "','" & PKGAdgvImpData.Rows(Line).Cells(1).Value & "')"
cmdsql = New SqlCommand(save, connsql)
cmdsql.ExecuteNonQuery()
Next
MsgBox("Data Saved Successfully")
PKGAdgvImpData.Columns.Clear()
End Sub
Thanks for Your Help.

Getting Dropdownlist selected value in vb.net

I am trying to set user account for my system. I have two tables (User and Staff)
And this is the interface for setting up user
the name dropdownlist need to be bound to staff table where I can display a list of staff members. When I insert these data to the user table I need to convert the selected staff name into its ID.
I'm really weak in programming and if possible help me with this.
this is the code I am using
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles btnUserAdd.Click
If ValidData() Then
Try
cmd.Connection = con
con.Open()
sel_id = Convert.ToString(cmbStaffName.SelectedValue)
cmd.CommandType = System.Data.CommandType.Text
cmd.CommandText = "Insert Into dbo.[User] (User_ID,Employee_ID,User_Name,Password,User_Level) values ('" & txtBoxUserID.Text & "','" & sel_id & "','" & txtBoxUserName.Text & "', '" & txtBoxPassword.Text & "','" & ComboBox1.Text & "')"
cmd.ExecuteNonQuery()
MsgBox("Succesfully Added", MsgBoxStyle.Information, "add")
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
con.Close()
End If
If Not ValidData() Then
Exit Sub
End If
End Sub
Private Sub btnUserUpdate_Click(sender As Object, e As EventArgs) Handles btnUserUpdate.Click
End Sub
Private Sub Setup_User_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'TODO: This line of code loads data into the 'MyHotelManagementSystemDataSet19.Staff' table. You can move, or remove it, as needed.
Me.StaffTableAdapter1.Fill(Me.MyHotelManagementSystemDataSet19.Staff)
'TODO: This line of code loads data into the 'MyHotelManagementSystemDataSet18.Staff' table. You can move, or remove it, as needed.
Me.User_TypeTableAdapter.Fill(Me.MyHotelManagementSystemDataSet17.User_Type)
End Sub
Private Sub cmbStaffName_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cmbStaffName.SelectedIndexChanged
Try
con.Open()
ds = New DataSet()
cmd = New SqlCommand("select * from Staff", con)
Adapter = New SqlDataAdapter(cmd)
adapter.Fill(ds)
cmbStaffName.DataSource = StaffBindingSource1
cmbStaffName.DisplayMember = "Name"
cmbStaffName.ValueMember = "Employee_ID"
Catch ex As Exception
Finally
con.Close()
End Try
End Sub
Private Sub cmbStaffName_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cmbStaffName.SelectedIndexChanged
Try
con.Open()
ds = New DataSet()
cmd = New SqlCommand("select * from Staff", con)
Using adapter as New SqlDataAdapter(cmd)
adapter.Fill(ds)
End Using
cmbStaffName.DisplayMember = "Name"
cmbStaffName.ValueMember = "Employee_ID"
cmbStaffName.DataSource = ds
Catch ex As Exception
Finally
con.Close()
End Try
End Sub

VB.net / SQL Adding Data

My question is somewhat complex but simple. I am building a small program to keep track of inventory. I created a view that contains a list of names and id in SQL. I then created a table so that I can add items to the names in SQL
IN vb.net
When the users clicks on the 1st datagridview - the name and number comes in separate text boxes. When they click the save button the records will then get saved to my table. (Which I have another Datagridview to show names and items. ) When I click my save button I get the following error:
Violation of PRIMARY KEY constraint 'PK_Inventory_Detail'. Cannot insert duplicate key in object 'dbo.Inventory_Detail'. The duplicate key value is (4 ).
I initially had the foreign key but then dropped based on the error but I am still getting it????
Imports System.Data.SqlClient
Public Class Form1
Dim cn As New SqlConnection("Data Source=;Initial Catalog=Inventory;User ID=;Password=")
Dim adap As New SqlDataAdapter("SELECT res_snbr, res_First_Name, res_Last_Name FROM ResidentInventoryView", cn)
Dim builder As New SqlCommandBuilder(adap)
Dim dt As New DataTable
Dim res_snbr As Object
'Dim InventoryDetailsBindingSource As New BindingSource
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load
' DataGridView1.AllowUserToAddRows = True
' DataGridView1.AllowUserToDeleteRows = True
DataGridView1.[ReadOnly] = False
'
adap.Fill(dt)
ResidentInventoryViewBindingSource.DataSource = dt
DataGridView1.DataSource = ResidentInventoryViewBindingSource
End Sub
Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged
If TextBox1.TextLength > 0 Then
ResidentInventoryViewBindingSource.Filter = String.Format("res_First_Name Like '%{0}%'", TextBox1.Text)
Else
ResidentInventoryViewBindingSource.Filter = String.Empty
End If
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Try
adap.Update(dt)
MessageBox.Show("Saved successfully")
Catch ex As Exception
MessageBox.Show("Error updating database")
End Try
End Sub
Private Sub DataGridView1_CellContentClick(sender As Object, e As DataGridViewCellEventArgs) Handles DataGridView1.CellContentClick
Dim i As Integer
i = DataGridView1.CurrentRow.Index
Me.rlastname.Text = DataGridView1.Item(0, i).Value
Me.rfname.Text = DataGridView1.Item(1, i).Value
Me.rnum.Text = DataGridView1.Item(2, i).Value
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
cn.Open()
Dim cmd As New SqlCommand(("Insert INTO Inventory_Detail Values('" & _
rnum.Text & "','" & _
rfname.Text & "','" & _
rnum.Text & "','" & _
txtitem.Text & "','" & _
"" & "','" & _
"" & "')"), cn)
cmd.ExecuteNonQuery()
cn.Close()
MsgBox("Success....", MsgBoxStyle.Information, "Success")
rnum.Clear()
rfname.Clear()
rnum.Clear()
txtitem.Clear()
End Sub
End Class
You already have an item in the Inventory_Detail table with the id of 4. You need to increment the id so that every record in the Inventory_Detail table has a unique id.
You can you the Identity property in SQL to Increment your Primary Key so you don't have to insert the id manually.
Identity MSDN
Or Consider using a GUID that way it is always unique.
Right, so what I did ( maybe not the best)
created a view to get all names and ids
Created one table - contains a primary key that auto Increments
has an id field
item
start date
end date
The above will allow one person to be assigned multiple items and keep track of the items

Adding data to Access Database through Visual Basic Form

I have a forum where I want the user to type a profile name and then click Add and then it will add what they typed in the text box the the ProfileName field in my table. When I click the Add button, it comes up with an error that says An unhandled exception of type System.Data.OleDb.OleDbException occurred in system.data.dll. Here is my code:
Private Sub RefreshData()
Dim cnn As New OleDb.OleDbConnection
If Not cnn.State = ConnectionState.Open Then
cnn.Open()
End If
Dim da As New OleDb.OleDbDataAdapter("SELECT id AS [ID], " & _
"ProfileName AS [Name] " & _
" FROM Profile ORDER BY id", cnn)
Dim dt As New DataTable
da.Fill(dt)
cnn.Close()
Me.dgvData.DataSource = dt
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
If (TextBox1.Text = "") Then
MsgBox("Please enter a profile name.")
Else
Dim cnn As New OleDb.OleDbConnection("Provider=Microsof… Source=c:\Data\Database.mdb ;Extended Properties=Paradox 5.x;")
Dim cmd As New OleDb.OleDbCommand
If Not cnn.State = ConnectionState.Open Then
cnn.Open()
End If
cmd.Connection = cnn
cmd.CommandText = "INSERT INTO Profile(ProfileName) " & _
"VALUES (" & Me.TextBox1.Text & "')"
cmd.ExecuteNonQuery()
cnn.Close()
Dim oForm As addsnake
oForm = New addsnake
oForm.Show()
oForm = Nothing
Me.Close()
End If
End Sub
Without further information I suggest that:
You don't need to give id an alias of ID:
SELECT id AS [ID]
you might still enclose it in square-brackets though, if you like:
SELECT [id]
You are missing an apostrophe in the following line:
"VALUES (" & Me.TextBox1.Text & "')"
Also check your connection string at connectionstrings.com

Resources