How to save integer and decimal datatype from datagridview to database ms access in VB.NET [duplicate] - vb.net

This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 3 years ago.
I have been searching for a solution for my code error, which says that there is a data mismatch to my database declared datatype. I am saving my data grid view's data into ms access database but it show an error of data mismatch for saving PRICE and QUANTITY data.
I have tried adding parameters and it shows the error System.NullReferenceException: 'Object reference not set to an instance of an object.'
'After comfirm only save in database
Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
If (MessageBox.Show("Comfrim the orders?", "Comfirmation", MessageBoxButtons.YesNo, MessageBoxIcon.Question) = DialogResult.Yes) Then
If OrderDataGridView.Rows.Count > 0 Then
DBConnect = New OleDbConnection
DBConnect.ConnectionString = "Provider=Microsoft.jet.oledb.4.0;data source = ViewOrder.mdb"
For i As Integer = OrderDataGridView.Rows.Count - 1 To 0 Step -1
Dim Query As String
Query = "INSERT INTO ViewOrder.Order (Serve,Table_No, Item_Code, Item_Name, Quantity, Price, Remarks)
VALUES (#Serve, #Table_No, #Item_Code, Item_Name, #Quantity, #Price, #Remarks)"
Dim cmd As New OleDb.OleDbCommand(Query, DBConnect)
cmd.Parameters.Add("#Serve", OleDbType.VarChar).Value = Label8.Text
cmd.Parameters.Add("#Table_No", OleDbType.VarChar).Value = Label10.Text
cmd.Parameters.Add("#Item_Code", OleDbType.VarChar).Value = OrderDataGridView.Rows(i).Cells(0).Value
cmd.Parameters.Add("#Item_Name", OleDbType.VarChar).Value = OrderDataGridView.Rows(i).Cells(1).Value
cmd.Parameters.Add("#Quantity", OleDbType.Integer).Value = OrderDataGridView.Rows(i).Cells(2).Value
cmd.Parameters.Add("#Price", OleDbType.Decimal).Value = OrderDataGridView.Rows(i).Cells(3).Value
cmd.Parameters.Add("#Remarks", OleDbType.VarChar).Value = OrderDataGridView.Rows(i).Cells(4).Value
DBConnect.Open()
Dim Reader As OleDbDataReader
Reader = command.ExecuteReader
DBConnect.Close()
Next
End If
End If
End Sub
But it still show the error.
This is my current code with the error of data mismatch.
Dim Query As String
Query = "INSERT INTO ViewOrder.Order (Serve,Table_No, Item_Code, Item_Name, Quantity, Price, Remarks) VALUES ('" & Label8.Text & "','" & Label10.Text & "','" & OrderDataGridView.Rows(i).Cells(0).Value & "', '" & OrderDataGridView.Rows(i).Cells(1).Value & "','" & OrderDataGridView.Rows(i).Cells(2).Value & "','" & OrderDataGridView.Rows(i).Cells(3).Value & "','" & OrderDataGridView.Rows(i).Cells(4).Value & "')"
Dim Reader As OleDbDataReader
command = New OleDbCommand(Query, DBConnect)
Reader = command.ExecuteReader
DBConnect.Close()
I just need to save the data in database.

From the MS Docs
the order in which OleDbParameter objects are added to the
OleDbParameterCollection must directly correspond to the position of
the question mark placeholder for the parameter in the command text.
Instead of question marks, I like to use parameter names. It is easier to see if I have the order correct. We add the parameters outside the loop because each iteration uses the same parameters. We don't want to keep adding them. Only the values change but not for Serve and TableNo which stay the same for all the Inserts.
Pass the connection string directly to the constructor of the connection.
The Using...End Using blocks ensure that your database objects are closed and disposed even if there is an error.
You do not want a reader for an Insert. A reader is for returned records. You need .ExecuteNonQuery.
You need to check the datatypes of the fields because I just guessed.
The DataGridView.Rows.Count is -2 because subtract one for counting starting at one and collections starting at zero. And subtract another one for the empty row at the bottom of the grid that is included in the count.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim Query As String = "INSERT INTO ViewOrder.Order (Serve,Table_No, Item_Code, Item_Name, Quantity, Price, Remarks)
Values(#Serve, #TableNo, #ItemCode,#ItemName, #Quantity, #Price, #Remarks);"
Using DBConnect = New OleDbConnection("Provider=Microsoft.jet.oledb.4.0;data source = ViewOrder.mdb")
Using cmd As New OleDbCommand(Query, DBConnect)
cmd.Parameters.Add("#Serve", OleDbType.VarChar).Value = Label8.Text
cmd.Parameters.Add("#TableNo", OleDbType.VarChar).Value = Label10.Text
cmd.Parameters.Add("#ItemCode", OleDbType.VarChar)
cmd.Parameters.Add("#ItemName", OleDbType.VarChar)
cmd.Parameters.Add("#Quantity", OleDbType.Integer)
cmd.Parameters.Add("#Price", OleDbType.Decimal)
cmd.Parameters.Add("#Remarks", OleDbType.VarChar)
DBConnect.Open()
For i As Integer = 0 To DataGridView1.Rows.Count - 2
cmd.Parameters("#ItemCode").Value = OrderDataGridView.Rows(i).Cells(0).Value
cmd.Parameters("#ItemName").Value = OrderDataGridView.Rows(i).Cells(1).Value
cmd.Parameters("#Quantity").Value = CInt(OrderDataGridView.Rows(i).Cells(2).Value)
cmd.Parameters("#Price").Value = CDec(OrderDataGridView.Rows(i).Cells(3).Value)
cmd.Parameters("#Remarks").Value = OrderDataGridView.Rows(i).Cells(4).Value
cmd.ExecuteNonQuery()
Next
End Using
End Using
End Sub

Related

Data type mismatch in criteria expression while updating password field

This is my Select & Update code for OLEDB DB.
I am getting a Data type mismatch in criteria expression error whilst changing the Password field value.
All four fields are set to Long Text datatype.
Update Query
con = Class1.dbconn
cmd = New OleDbCommand("Update User_details set User_ID ='" & TextBox1.Text & "', User_Name='" & TextBox2.Text & "', [Password]='" & TextBox3.Text & "' where Sno='" & Label4.Text & "'", con)
cmd.ExecuteNonQuery()
MessageBox.Show("User Details Updated")
Select Query
cmd = New OleDbCommand("select * from User_details where User_ID='" & TextBox1.Text & "'", con)
Dim dr As OleDbDataReader
dr = cmd.ExecuteReader
If dr.Read Then
Label4.Text = dr("Sno").ToString
TextBox2.Text = dr("User_Name").ToString
TextBox3.Text = dr("Password").ToString
TextBox2.Text = TextBox2.Text.Replace(" ", "")
TextBox3.Text = TextBox3.Text.Replace(" ", "")
dr.Close()
End If
Keep your database objects local so you can control when they are closed and disposed. Using...End Using blocks take care of this for you even if there is an error. The Using blocks demonstrated here take care of both the connection and the command. Note the comma after the connection line.
Always use Parameters. Not only does it make your command text easier to read and write (without all the quotes, double quotes and ampersands) but it protects your database from the destruction of Sql injection. When you are using the OleDb provider it is essential that order that the parameters appear in the command text match the order they are added to the parameters collection. Unlike Sql Server, Access pays no attention to the names of the parameters; only the order.
Notice that the connection is not opened until right before the .Execute... and is closed (with the End Using) directly after. Connections are precious resources. I used a DataTable instead of a DataReader in the SelectUser sub so I could close the connection before updated the user interface. In the UpdatePassword sub the connection is closed before showing the MessageBox. After all the end user could have gone to lunch and there would be your connection flapping in the breeze.
As far as the type mis-match check the links provided by #Jimi and then check your database to see if the OleDbType matches.
Private Sub UpdatePassword()
Using con As New OleDbConnection("Your connection string"),
cmd As New OleDbCommand("Update User_details set User_ID = #ID, User_Name = #Name, [Password]= #Password Where Sno= #Sno;", con)
With cmd.Parameters
.Add("#ID", OleDbType.LongVarChar).Value = TextBox1.Text
.Add("#Name", OleDbType.LongVarChar).Value = TextBox2.Text
.Add("#Password", OleDbType.LongVarChar).Value = TextBox3.Text
.Add("#Sno", OleDbType.LongVarChar).Value = Label4.Text
End With
con.Open()
cmd.ExecuteNonQuery()
End Using
MessageBox.Show("User Details Updated")
End Sub
Private Sub SelectUser()
Dim dt As New DataTable
Using con As New OleDbConnection("Your connection string"),
cmd As New OleDbCommand("select * from User_details where User_ID= #ID;", con)
cmd.Parameters.Add("#ID", OleDbType.LongVarChar).Value = TextBox1.Text
con.Open()
dt.Load(cmd.ExecuteReader)
End Using
If dt.Rows.Count > 0 Then
Dim row As DataRow = dt.Rows(0)
Label4.Text = row("Sno").ToString
TextBox2.Text = row("User_Name").ToString
TextBox3.Text = row("Password").ToString
TextBox2.Text = TextBox2.Text.Replace(" ", "")
TextBox3.Text = TextBox3.Text.Replace(" ", "")
End If
End Sub
Finally, you should NEVER store passwords as plain text. They should be salted and hashed. I will leave it to you to research how to do this.

System.Data.SqlClient.SqlException: Violation of PRIMARY KEY

I create a SQL Server database and I want to add some data in a particular table of that database. I use some textbox to input the data and an add button to complete. But when I tap the button the whole process was stopped and indicate an error in the DBSQL module which is shown below.
Here's my code:
Imports System.Data
Imports System.Data.SqlClient
Module DBSQLServer
Public con As New SqlConnection("Data Source=JOYALXDESKTOP\SQLEXPRESS;Initial Catalog=SaleInventory;Integrated Security=True")
Public cmd As New SqlCommand
Public da As New SqlDataAdapter
Public ds As New DataSet
Public dt As DataTable
Public qr As String
Public i As Integer
Public Function searchdata(ByVal qr As String) As DataSet
da = New SqlDataAdapter(qr, con)
ds = New DataSet
da.Fill(ds)
Return ds
End Function
Public Function insertdata(ByVal qr As String) As Integer
cmd = New SqlCommand(qr, con)
con.Open()
i = cmd.ExecuteNonQuery()
con.Close()
Return i
End Function
End Module
The error occurs on this line:
i = cmd.ExecuteNonQuery()
In the table, I have 5 columns:
ProID, ProName, ProDesc, ProPrice, ProStock
ProID is my primary key.
Here's my add button code to add the data into the database:
Private Sub Add_Click(sender As Object, e As EventArgs) Handles add.Click
If (isformvalid()) Then
qr = "Insert into tblProductInfo (ProName, ProDesc, ProPrice, ProStock) Values('" & nametext.Text & "','" & descriptiontext.Text & "','" & pricetext.Text & "','" & stocktext.Text & "')"
Dim logincorrect As Boolean = Convert.ToBoolean(insertdata(qr))
If (logincorrect) Then
MsgBox("Stock Added Successfully ...", MsgBoxStyle.Information)
Else
MsgBox("Something Wrong. Record Not Saved. Please Check and Try Again...", MsgBoxStyle.Critical)
End If
End If
End Sub
When my query is:
qr = "Insert into tblProductInfo (ProName, ProDesc, ProPrice, ProStock) Values('" & nametext.Text & "','" & descriptiontext.Text & "','" & pricetext.Text & "','" & stocktext.Text & "')"
The error is below :
System.Data.SqlClient.SqlException: 'Cannot insert the value NULL into column 'ProID', table 'SaleInventory.dbo.tblProductInfo'; column does not allow nulls. INSERT fails.
And when my query is:
qr = "Insert into tblProductInfo (ProID, ProName, ProDesc, ProPrice, ProStock) Values('" & idtext.Text & "','" & nametext.Text & "','" & descriptiontext.Text & "','" & pricetext.Text & "','" & stocktext.Text & "')" `
Then the error is:
System.Data.SqlClient.SqlException: 'Violation of PRIMARY KEY constraint 'PK_tblProductInfo'. Cannot insert duplicate key in object 'dbo.tblProductInfo'. The duplicate key value is (1).
This is because in tblProductInfo there is a row with ProID=1. You should code so that avoid this duplicate, for example you can first run a script to find the maximum of ProID in your table ("Select MAX(ProID) from tblProductInfo"), and run your query with MAX(ProID)+1.
Assuming you have corrected your database making the ProdID an identity field.
Notice that all interaction with the user interface is performed in the Form code. All interaction with the database is performed in the Module. Although you still need to Import System.Data (for the DataTable type) it is not necessay to Import System.Data.SqlClient in the Form. All validation is done in the Form.
In the Module code, the Using...EndUsing blocks ensure that your database objects are closed and disposed even if there is an error. I have demonstrated how to use parameters to avoid Sql injection but I had to guess at the datatypes. Check your database for the actual datatypes and adjust the SqlDbType and the parameter types and the validation code in the Form accordingly.
Connections are precious resources. Notice that the connection is opened at the last minute and closed and disposed by the End Using immediately after it is used by and .Execute...
Module DBSQLServer
Private conString As String = "Data Source=JOYALXDESKTOP\SQLEXPRESS;Initial Catalog=SaleInventory;Integrated Security=True"
'Example of how your search function might look.
Public Function searchdata(Name As String) As DataTable
Dim dt As New DataTable
Using cn As New SqlConnection()
Using cmd As New SqlCommand("Select * From tblProductInfo Where Name = #Name", cn)
cmd.Parameters.Add("#Name", SqlDbType.VarChar).Value = Name
cn.Open()
dt.Load(cmd.ExecuteReader)
End Using
End Using
Return dt
End Function
Public Function insertdata(Name As String, Description As String, Price As Decimal, Stock As Integer) As Integer
Dim i As Integer
Using cn As New SqlConnection(conString)
Using cmd As New SqlCommand("Insert into tblProductInfo (ProName, ProDesc, ProPrice, ProStock) Values(#Name,#Description, #Price, #Stock", cn)
With cmd.Parameters
.Add("#Name", SqlDbType.VarChar).Value = Name
.Add("#Description", SqlDbType.VarChar).Value = Description
.Add("#Price", SqlDbType.Decimal).Value = Price
.Add("#Stock", SqlDbType.Int).Value = Stock
End With
cn.Open()
i = cmd.ExecuteNonQuery
End Using
End Using
Return i
End Function
End Module
And in the form
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
'First check that text boxes for string parameters are filled in
If nametext.Text = "" OrElse descriptiontext.Text = "" Then
MessageBox.Show("Please fill in all text boxes.")
Return
End If
'Next check for valid numeric values
Dim price As Decimal
If Not Decimal.TryParse(pricetext.Text, price) Then
MessageBox.Show("The price must be a number.")
Return
End If
Dim stock As Integer
If Not Integer.TryParse(stocktext.Text, stock) Then
MessageBox.Show("Stock must be a whole number")
Return
End If
Dim retVal As Integer = DBSQLServer.insertdata(nametext.Text, descriptiontext.Text, price, stock)
If retVal = 1 Then
MessageBox.Show("Product successfully added.")
End If
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim dt = DBSQLServer.searchdata(txtSearch.Text)
DataGridView1.DataSource = dt
End Sub

How to determine if a record already exists in VB.net?

I'm doing a VB with Access database and I want to create a button. Which savebutton with checking where the data that try to insert is duplicated or not compare with my database.
This my code, and the problem is whatever I enter it just show the user already exists.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
MyConn = New OleDbConnection
MyConn.ConnectionString = connString
MyConn.Open()
If (ComboBox2.Text = "") And (ComboBox3.Text = "")
And (TextBox3.Text = "") And (ComboBox4.Text = "")
Then
MsgBox("Please fill-up all fields!")
Else
Dim theQuery As String = ("SELECT * FROM Table1
WHERE"" [Subject_Code]=#Subject_Code ,[Day]=#Day,
[Times]=#Times , [Lecture]=#Lecture and [Class_Room]=#Class_Room""")
Dim cmd1 As OleDbCommand = New OleDbCommand(theQuery, MyConn)
cmd1.Parameters.AddWithValue("#Subject_Code", TextBox6.Text)
cmd1.Parameters.AddWithValue("#Day", ComboBox2.Text)
cmd1.Parameters.AddWithValue("#Times", ComboBox3.Text)
cmd1.Parameters.AddWithValue("#Lecture", TextBox3.Text)
cmd1.Parameters.AddWithValue("#Class_Room", ComboBox4.Text)
Using reader As OleDbDataReader = cmd1.ExecuteReader()
If reader.HasRows Then
'User already exists
MsgBox("User Already Exist!")
Else
Dim Update As String = "INSERT INTO [Table1]
([Subject_Code], [Subject],
[Day], [Times], [Level],[Semester], [Lecture],[Class], [Class_Room])
VALUES (?,?,?,?,?,?,?,?,?)"
Using cmd = New OleDbCommand(Update, MyConn)
cmd.Parameters.AddWithValue("#p1", TextBox6.Text)
cmd.Parameters.AddWithValue("#p2", TextBox1.Text)
cmd.Parameters.AddWithValue("#p3", ComboBox2.Text)
cmd.Parameters.AddWithValue("#p4", ComboBox3.Text)
cmd.Parameters.AddWithValue("#p5", ComboBox1.Text)
cmd.Parameters.AddWithValue("#p6", ComboBox6.Text)
cmd.Parameters.AddWithValue("#p7", TextBox3.Text)
cmd.Parameters.AddWithValue("#p8", ComboBox5.Text)
cmd.Parameters.AddWithValue("#p9", ComboBox4.Text)
MsgBox("New Data Is Saved")
cmd.ExecuteNonQuery()
End Using
End If
End Using
End If
First of all take a quick look at your theQuery variable, it may just have been malformed from where you have typed it into SO, but if not try:
Dim theQuery As String = "SELECT * FROM Table1 " &
"WHERE [Subject_Code] = #Subject_Code " &
"AND [Day] = #Day " &
"AND [Times] = #Times " &
"AND [Lecture] = #Lecture " &
"AND [Class_Room] = #Class_Room"
Your check for a pre existing user is based upon 5 fields, the insert for new data has 9 fields. Without knowing the business case I can't be sure if this is correct or if the missing 4 fields are actually important to the check and causing unexpected rows to be returned.
Personally my next steps would be:
Put a breakpoint on the AddWithValue statements and check the values
are what you expect
Run the query with the values in SSMS/Access or equivalent and check the rows that come back are what you expect

ExecuteReader: CommandText property has not been initialized when trying to make a register form for my database

hello guys im trying to script a register form for my database and i came with this code >> so can anyone help ?
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Dim cn As New SqlConnection
Dim cmd As New SqlCommand
Dim dr As SqlDataReader
cn.ConnectionString = "Server=localhost;Database=test;Uid=sa;Pwd=fadyjoseph21"
cmd.Connection = cn
cmd.CommandText = "INSERT INTO test2(Username,Password) VALUES('" & TextBox1.Text & "','" & TextBox2.Text & "')"
cn.Open()
dr = cmd.ExecuteReader
If dr.HasRows Then
MsgBox("You're already registered")
Else
MsgBox("Already registered")
End If
End Sub
Edit your Code in this way..
cmd.CommandText = "INSERT INTO User_Data(Username,Password) VALUES('" & TextBox1.Text & "' , '" & TextBox2.Text & "')"
cn.Open()
cmd.ExecuteNonQuery()
cn.Close()
Insert will not retrieve any records it's a SELECT statement you want to use .I'll suggest you use stored procedures instead to avoid Sql-Injections.
ExecuteReader it's for "SELECT" queries, that helps to fill a DataTable. In this case you execute command before cmd.commandText is defined.
You should have define cmd.commandText before and use ExecuteNonQuery after, like this.
Dim cn As New SqlConnection
Dim cmd As New SqlCommand
cn.ConnectionString = "Server=localhost;Database=test;Uid=sa;Pwd=fadyjoseph21"
cmd.Connection = cn
cn.Open()
cmd.CommandText = "INSERT INTO User_Data(Username,Password) VALUES('" & TextBox1.Text & "','" & TextBox2.Text & "')"
cmd.ExecuteNonQuery()
cn.Close()
cmd.CommandText should be assigned stored proc name or actual raw SQL statement before calling cmd.ExecuteReader
Update:
Change code as follows
....
cmd.Connection = cn
cmd.CommandText = "select * from TblToRead where <filter>" ''This is select query statement missing from your code
cn.Open()
dr = cmd.ExecuteReader ....
where <filter> will be something like username = "' & Request.form("username') & '" '
The error itself is happening because you're trying to execute a query before you define that query:
dr = cmd.ExecuteReader
'...
cmd.CommandText = "INSERT INTO User_Data(Username,Password) VALUES('" & TextBox1.Text & "' and '" & TextBox2.Text & "')"
Naturally, that doesn't make sense. You have to tell the computer what code to execute before it can execute that code:
cmd.CommandText = "INSERT INTO User_Data(Username,Password) VALUES('" & TextBox1.Text & "' and '" & TextBox2.Text & "')"
'...
dr = cmd.ExecuteReader
However, that's not your only issue...
You're also trying to execute a DataReader, but your SQL command doesn't return data. It's an INSERT command, not a SELECT command. So you just need to execute it directly:
cmd.CommandText = "INSERT INTO User_Data(Username,Password) VALUES('" & TextBox1.Text & "' and '" & TextBox2.Text & "')"
cmd.ExecuteNonQuery
One value you can read from an INSERT command is the number of rows affected. Something like this:
cmd.CommandText = "INSERT INTO User_Data(Username,Password) VALUES('" & TextBox1.Text & "' and '" & TextBox2.Text & "')"
Dim affectedRows as Int32 = cmd.ExecuteNonQuery
At this point affectedRows will contain the number of rows which the query inserted successfully. So if it's 0 then something went wrong:
If affectedRows < 1 Then
'No rows were inserted, alert the user maybe?
End If
Additionally, and this is important, your code is wide open to SQL injection. Don't directly execute user input as code in your database. Instead, pass it as a parameter value to a pre-defined query. Basically, treat user input as values instead of as executable code. Something like this:
cmd.CommandText = "INSERT INTO User_Data(Username,Password) VALUES(#Username,#Password)"
cmd.Parameters.Add("#Username", SqlDbType.NVarChar, 50).Value = TextBox1.Text
cmd.Parameters.Add("#Password", SqlDbType.NVarChar, 50).Value = TextBox2.Text
(Note: I guessed on the column types and column sizes. Adjust as necessary for your table definition.)
Also, please don't store user passwords as plain text. That's grossly irresponsible to your users and risks exposing their private data (even private data on other sites you don't control, if they re-use passwords). User passwords should be obscured with a 1-way hash and should never be retrievable, not even by you as the system owner.
You're attempting to change the CommandText after you're executing your query.
Try this:
Private cn = New SqlConnection("Server=localhost;Database=test;UID=sa;PWD=secret")
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Dim cmd As New SqlCommand
cmd.CommandText = "select * from table1" ' your sql query selecting data goes here
Dim dr As SqlDataReader
cmd.Connection = cn
cn.Open()
dr = cmd.ExecuteReader
If dr.HasRows = 0 Then
InsertNewData(TextBox1.Text, TextBox2.Text)
Else
MsgBox("Already registered")
End If
End Sub
Private Sub InsertNewData(ByVal username As String, ByVal password As String)
Dim sql = "INSERT INTO User_Data(Username,Password) VALUES(#Username, #Password)"
Dim args As New List(Of SqlParameter)
args.Add(New SqlParameter("#Username", username))
args.Add(New SqlParameter("#Password", password))
Dim cmd As New SqlCommand(sql, cn)
cmd.Parameters.AddRange(args.ToArray())
If Not cn.ConnectionState.Open Then
cn.Open()
End If
cmd.ExecuteNonQuery()
cn.Close()
End Sub
This code refers the INSERT command to another procedure where you can create a new SqlCommand to do it.
I've also updated your SQL query here to use SqlParameters which is much more secure than adding the values into the string directly. See SQL Injection.
The InsertNewData method builds the SQL Command with an array of SQLParameters, ensures that the connection is open and executes the insert command.
Hope this helps!

Adding data from Text boxes directly to database and viewing updated gridview

still very new to this and can't seem to find exactly what I'm looking for. Quick run-through on what I'm trying to accomplish. I have a datagridview (3 columns - Id, Name, Address) that is connected to a local .mdf database file, that I'm able to search through using a search textbox. My goal NOW is to submit records into the database directly using 2 text fields and the Id field to automatically increment. (Id++, txtName.Text, txtAddress.Text) and to use a send button(btnSend) to activate this event.(PLEASE KEEP IN MIND, MY GOAL IS TO HAVE EVERYONE INCLUDING THE NEW RECORD SHOW UP IN THE DATAGRIDVIEW AND FOR THE NEW ROW TO BE INSERTED DIRECTLY TO THE DATABASE AND SAVE ANY CHANGES) I've been hammering at this for a couple days now and would appreciate any help. Below is my code, but please keep in mind I'm still new and trying to figure this language out so if there's any unnecessary code, please do let me know... Also if you want to help with one additional thing, maybe some code on how to export that table to a different file from an export button. Thanks! I'm currently also getting an error saying "Cannot find table 0." when I click the btnSend button.
Public Sub btnSend_Click(ByVal sender As Object, e As EventArgs) Handles btnSend.Click
Try
Dim connectionString As String
Dim connection As SqlConnection
Dim ds As New DataSet("Table")
Dim dataset As New DataSet()
Dim sqlInsert As String
Dim sqlSelect As String
Dim Id As Integer = 5
Dim newRow As DataRow = dataset.Tables(0).NewRow()
connectionString = "Data Source=(LocalDB)\v11.0;AttachDbFilename=""" & My.Application.Info.DirectoryPath & "\Database1.mdf"";Integrated Security=True;"
sqlInsert = "INSERT INTO Table (#Id, #Name, #Address) VALUES (" & Id & ", '" & txtName.Text & "','" & txtAddress.Text & "')"
sqlSelect = "SELECT * FROM Table"
connection = New SqlConnection(connectionString)
Dim da As New SqlDataAdapter()
connection.Open()
da.Fill(ds)
Using da
da.SelectCommand = New SqlCommand(sqlSelect)
da.InsertCommand = New SqlCommand(sqlInsert)
da.InsertCommand.Parameters.Add(New SqlParameter("Id", SqlDbType.Int, 4, Id))
da.InsertCommand.Parameters.Add(New SqlParameter("Name", SqlDbType.NText, 50, txtName.Text))
da.InsertCommand.Parameters.Add(New SqlParameter("Address", SqlDbType.NText, 50, txtAddress.Text))
Using dataset
da.Fill(dataset)
newRow("Id") = Id
newRow("Name") = txtName.Text
newRow("Address") = txtAddress.Text
dataset.Tables(0).Rows.Add(newRow)
da.Update(dataset)
End Using
Using newDataSet As New DataSet()
da.Fill(newDataSet)
End Using
End Using
connection.Close()
Catch ex As Exception
MsgBox(ex.Message)
Throw New Exception("Problem loading persons")
End Try
Dim updatedRowCount As String = gvDataViewer.RowCount - 1
lblRowCount.Text = "[Total Row Count: " & updatedRowCount & "]"
End Sub