Adding data from Text boxes directly to database and viewing updated gridview - vb.net

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

Related

How to update access db by editing datagridview cells?

Im trying to edit items after inserting to access by clicking the save button? How can i save the edits done in datagridview rows to access?
Already tried the update query
For each loop
vb.net
Private Sub BunifuFlatButton1_Click(sender As Object, e As EventArgs) Handles BunifuFlatButton1.Click
Dim constring As String = ("Provider=Microsoft.ACE.OLEDB.12.0;Data Source= C:\Users\PU-IMO\Desktop\BlueWavesIS - Copy\BlueWavesIS\BlueWavesIS.accdb")
Dim conn As New OleDbConnection(constring)
For Each row As DataGridViewRow In DataGridView1.Rows
Using con As New OleDbConnection(constring)
'nettxt.Text = (grosstxt.Text * perdistxt.Text / 100) - (dislctxt.Text + disusd.Text + distax.Text)
Dim cmd As New OleDbCommand("Update PurchaseInvoice set [Itemnum] = #ItemNum, [Itemname]= #ItemName, [Itemqty]= #ItemQty, [Itemprice] = #ItemPrice, [discount] =#discount, [subtotal] = #subtotal,[Preference] = " & preftxt.Text & ", [Suppnum] = " & pnumtxt.Text & ", [UniqueID] = " & pautotxt.Text & " Where [UniqueID] = " & pautotxt.Text & "", con)
cmd.Parameters.AddWithValue("#ItemID", row.Cells("ItemID").Value)
cmd.Parameters.AddWithValue("#ItemName", row.Cells("ItemName").Value)
cmd.Parameters.AddWithValue("#ItemQty", row.Cells("ItemQty").Value)
cmd.Parameters.AddWithValue("#ItemPrice", row.Cells("ItemPrice").Value)
cmd.Parameters.AddWithValue("#discount", row.Cells("discount").Value)
cmd.Parameters.AddWithValue("#subtotal", row.Cells("subtotal").Value)
cmd.Parameters.AddWithValue("#Ref", preftxt.Text.ToString)
cmd.Parameters.AddWithValue("#Suppnum", Convert.ToInt32(pnumtxt.Text))
cmd.Parameters.AddWithValue("#UniqueID", Convert.ToInt32(pautotxt.Text))
DataGridView1.AllowUserToAddRows = False
con.Open()
cmd.ExecuteNonQuery()
con.Close()
End Using
Next
'This the code i used to show the data in datagridview:
Private Sub NewPurchaseInvoice_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim con As New OleDbConnection
con.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source= C:\Users\PU-IMO\Desktop\BlueWavesIS - Copy\BlueWavesIS\BlueWavesIS.accdb"
con.Open()
Dim sql As String = "Select [Itemnum],[Itemname],[Itemprice],[ItemQty],[discount],[subtotal] from PurchaseInvoice where [UniqueID] = " & pautotxt.Text & ""
Dim cmd10 As OleDbCommand = New OleDbCommand(Sql, con)
'Dim adap As New OleDbDataAdapter("Select [Itemnum],[Itemname],[Itemprice],[discount],[subtotal] from PurchaseInvoice where UniqueID = " & pautotxt.Text & "", con)
'Dim ds As New System.Data.DataSet
'adap.Fill(ds, "PurchaseInvoice")
Dim dr As OleDbDataReader = cmd10.ExecuteReader
Do While dr.Read()
DataGridView1.Rows.Add(dr("ItemNum"), dr("ItemName"), dr("ItemQty"), dr("ItemPrice"), dr("discount"), dr("subtotal"))
Loop
con.Close()
I expect that all the rows will be updated as each other, but the actual output is that each row has different qty name etc...
This code does not seem appropriate in the load event because pautotxt.Text will not have a value yet. Can you move it to a Button.Click?
I guessed that the datatype of ID is an Integer. You must first test if the the .Text property can be converted to an Integer. .TryParse does this. It returns a Boolean and fills IntID that was provided as the second parameter.
You can 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 can pass the Select statement and the connection directly to the constructor of the command.
ALWAYS use Parameters, never concatenate strings to avoid sql injection. Don't use .AddWithValue. See http://www.dbdelta.com/addwithvalue-is-evil/
and
https://blogs.msmvps.com/jcoehoorn/blog/2014/05/12/can-we-stop-using-addwithvalue-already/
and another one:
https://dba.stackexchange.com/questions/195937/addwithvalue-performance-and-plan-cache-implications
The DataAdapter will open the connection, fiil the DataTable and close the connection if it finds it closed; however if it is found open it will leave it open.
The last line binds the grid to the DataTable.
Private Sub FillGrid()
If Not Integer.TryParse(pautotxt.Text, IntID) Then
MessageBox.Show("Please enter a number")
Return
End If
dt = New DataTable()
Using con As New OleDbConnection(ConnString)
Using cmd As New OleDbCommand(Sql, con)
cmd.Parameters.Add("#ID", OleDbType.Integer).Value = IntID
Dim adap = New OleDbDataAdapter(cmd)
adap.Fill(dt)
End Using
End Using
DataGridView1.DataSource = dt
End Sub
DataTables are very clever. When bound to a DataGridView they keep track of changes and mark rows as update, insert, or delete. The DataAdapter uses this info to update the database. Once the database is updated we call .AcceptChanges on the DataTable to clear the marking on the rows.
Private Sub UpdateDatabase()
Using cn As New OleDbConnection(ConnString)
Using da As New OleDbDataAdapter(Sql, cn)
da.SelectCommand.Parameters.Add("#ID", OleDbType.Integer).Value = IntID
Using builder As New OleDbCommandBuilder(da)
da.Update(dt)
End Using
End Using
End Using
dt.AcceptChanges()
End Sub

Syntax Error near Insert Statement

I am trying to insert data in Access database but getting a Syntax error exception :( What am I doing wrong ?
Private Sub savebtn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles savebtn.Click
Dim con As OleDb.OleDbConnection = New OleDb.OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=E:\vb8\Mini-project\Mini-project\mini_db.mdb")
Dim query As String
Try
con.Open()
query = "INSERT INTO minitab VALUES (" & TextBox1.Text & "," & TextBox2.Text & ",#dob ," & TextBox5.Text & "," & TextBox6.Text & "," & TextBox7.Text & "," & TextBox8.Text & "," & TextBox9.Text & ")"
Dim da As OleDb.OleDbDataAdapter = New OleDb.OleDbDataAdapter(query, con)
Dim dt As New DataTable
da.Fill(dt)
MsgBox("Data has been saved", MsgBoxStyle.SystemModal, "ok")
Catch ex As Exception
MsgBox(ex.Message)
End Try
con.Close()
End Sub
You are adding values in your Insert statement without addressing the columns. Now, this is not necessary if you put the values in the correct order so I suggest you to check it again. However, if you specify the column names then your insert statement might look like:
"INSERT INTO minitab(column1,Column2,Column3)VALUES(#col1,#col2,#col3)",connectiontring
cmd.Parameters.Add("#col1",OleDbType.VarChar).Value = TxtBox1.Text 'make sure to set the datatype correctly
cmd.Parameters.Add("#col2",OleDbType.VarChar).Value = TxtBox2.Text
.........
cmd.ExecuteNonQuery
And most importantly, what are you trying to do? If you are trying to insert data, then why are you using a DataTable? The code above will let you insert data into the database. However, a datatable is used to get data from the database and display it. Also DataTables have change tracking and are used in conjunction with DataAdapters to perform CRUD operations.
However, to use a DataTable to display data, you can try this:
Dim cmd as new OleDbCommand("Select * from minitab",connectionstring)
Dim dt as new DataTable
Dim ada as new OleDbDataAdapter(cmd)
ada.Fill(dt)
To display the data, you can use various controls. One of them is a DataGridView.
DataGridView1.DataSource = dt
Hope you understand :)

Can't INSERT INTO access database

I can select the data from an Access database, but I tried many ways to INSERT INTO database. There is no error message, but it didn't insert the data.
Code:
Dim conn As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & CurDir() & "\fsDB1.accdb")
Dim cmd As OleDbCommand
Dim dr As OleDbDataReader
conn.Open()
Dim CommandString As String = "INSERT INTO tblfile(stdUname,filePw,filePath,status) VALUES('" & userName & "','" & filePw & "','" & filePath & "','A')"
Dim command As New OleDbCommand(CommandString, conn)
Command.Connection = conn
Command.ExecuteNonQuery()
I just want a simple easy way to INSERT INTO an Access database. Is it possible because of the problem of Access database? I can insert this query by running query directly in Access.
Firstly I would check the database settings. If your app copies a new copy of the database each time you run it that would explain why you can select existing data and why your new data is not being saved (Well it is being saved, but the database keeps getting replaced with the old one). Rather set it up to COPY IF NEWER.
Further, you should ALWAYS use parameterized queries to protect your data. It is also is less error prone than string concatenated commands ans is much easier to debug.
Also, I recommend using a USING block to handle database connections so that your code automatically disposes of resources no longer needed, just in case you forget to dispose of your connection when you are done. Here is an example:
Using con As New OleDbConnection
con.ConnectionString = "Provider = Microsoft.ACE.OLEDB.12.0; " & _
"Data Source = "
Dim sql_insert As String = "INSERT INTO Tbl (Code) " & _
"VALUES " & _
"(#code);"
Dim sql_insert_entry As New OleDbCommand
con.Open()
With sql_insert_entry
.Parameters.AddWithValue("#code", txtCode.Text)
.CommandText = sql_insert
.Connection = con
.ExecuteNonQuery()
End With
con.Close()
End Using
Here is an example where data operations are in a separate class from form code.
Calling from a form
Dim ops As New Operations1
Dim newIdentifier As Integer = 0
If ops.AddNewRow("O'brien and company", "Jim O'brien", newIdentifier) Then
MessageBox.Show($"New Id for Jim {newIdentifier}")
End If
Back-end class where the new primary key is set for the last argument to AddNewRow which can be used if AddNewRow returns true.
Public Class Operations1
Private Builder As New OleDbConnectionStringBuilder With
{
.Provider = "Microsoft.ACE.OLEDB.12.0",
.DataSource = IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Database1.accdb")
}
Public Function AddNewRow(
ByVal CompanyName As String,
ByVal ContactName As String,
ByRef Identfier As Integer) As Boolean
Dim Success As Boolean = True
Dim Affected As Integer = 0
Try
Using cn As New OleDbConnection With {.ConnectionString = Builder.ConnectionString}
Using cmd As New OleDbCommand With {.Connection = cn}
cmd.CommandText = "INSERT INTO Customer (CompanyName,ContactName) VALUES (#CompanyName, #ContactName)"
cmd.Parameters.AddWithValue("#CompanyName", CompanyName)
cmd.Parameters.AddWithValue("#ContactName", ContactName)
cn.Open()
Affected = cmd.ExecuteNonQuery()
If Affected = 1 Then
cmd.CommandText = "Select ##Identity"
Identfier = CInt(cmd.ExecuteScalar)
Success = True
End If
End Using
End Using
Catch ex As Exception
Success = False
End Try
Return Success
End Function
End Class

How to insert listview items into 3 different tables VB.net

I'm trying to make a library system. I have a listview and it contains items to be inserted into different tables, (b_borrow_tbl, for the books , d_borrow_tbl for the multimedia, and m_borrow_tbl for the module).
I'm using this code to insert items to b_borrow_tbl:
Dim myconnection As New SqlConnection("Data Source = .\SqlExpress;Initial Catalog = librarysystemdb; Integrated Security = True")
selecteduser = cmb_borrower.SelectedValue
myconnection.Open()
For xa = 0 To ListView1.Items.Count - 1
Dim mycommand As New SqlCommand("Insert into b_borrow_tbl (bid,user_id,dateborrowed,aid,status) values(#bid,#user,#dateborrowed,#admin ,'" & "Borrowed" & "')", myconnection)
mycommand.Parameters.AddWithValue("bid", ListView1.Items(xa).SubItems(5).Text)
mycommand.Parameters.AddWithValue("user", selecteduser)
mycommand.Parameters.AddWithValue("dateborrowed", datestring)
mycommand.Parameters.AddWithValue("admin", LoginPage.admin)
mycommand.ExecuteNonQuery()
myconnection.Close()
Next
MsgBox("Transaction Saved")
ListView1.Items.Clear()
myconnection.Close()
End Sub
Here's one possibility. Note that I can't give you exact code because I don't know the structure of your other tables...so, with that caveat...
Dim myconnection As New SqlConnection("Data Source = .\SqlExpress;Initial Catalog = librarysystemdb; Integrated Security = True")
selecteduser = cmb_borrower.SelectedValue
myconnection.Open()
For xa = 0 To ListView1.Items.Count - 1
Dim itemType as String
itemType = ListView1.Items(xa).Subitems(6).Text ' Not sure abt col #
if itemType="Books" Then
Dim mycommand As New SqlCommand("Insert into b_borrow_tbl (bid,user_id,dateborrowed,aid,status) values(#bid,#user,#dateborrowed,#admin ,'" & "Borrowed" & "')", myconnection)
mycommand.Parameters.AddWithValue("bid", ListView1.Items(xa).SubItems(5).Text)
mycommand.Parameters.AddWithValue("user", selecteduser)
mycommand.Parameters.AddWithValue("dateborrowed", datestring)
mycommand.Parameters.AddWithValue("admin", LoginPage.admin)
mycommand.ExecuteNonQuery()
End If
If itemType="Multimedia" Then
mycommand.SqlCommand="Insert into d_borrow_table( field1,field2,etc) values (#parm1,#parm2,...)
mycommand.Parameters.Clear()
mycommand.Parameters.AddWithValue("#param1",value)
' etc
mycommand.ExecuteNonQuery()
' Then repeat by changing command text for third table
' clearing/defining parameters, then executing the query
End If
myconnection.Close()
Next
MsgBox("Transaction Saved")
ListView1.Items.Clear()
myconnection.Close()
End Sub
All we're doing here is "resetting" the "mycommand" variable with a new INSERT statement, clearing the parameters, and redefining them for the second and third inserts. Note that the connection isn't closed until after all three inserts have fired. You'll obviously need to replace the "placeholders" of "field1,field2" and #param1,#param2 etc with the actual fields from your tables, but I think that should give you a push in the right direction.

Adding SQL Parameter fails

This is a new concept for me and I can't quite see what's causing the error
I'm attempting to populate a datagridview control from a single field in an Access database (from a combo and Text box source).
Using literals works, but not with the parameter.
Dim conn As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & Backend & ";Persist Security Info=False;")
Dim command As New OleDbCommand("Select Year from tblTest ", conn)
Dim criteria As New List(Of String)
If Not cboYear.Text = String.Empty Then
criteria.Add("Year = #Year")
command.Parameters.AddWithValue("#Year", cboYear.Text)
End If
If criteria.Count > 0 Then
command.CommandText &= " WHERE " & String.Join(" AND ", criteria)
End If
Dim UserQuery As New OleDbDataAdapter(command.CommandText, conn)
Dim UserRet As New DataTable
UserQuery.Fill(UserRet)
With frmDGV.DataGridView2
.DataSource = UserRet
End With
frmDGV.DataGridView2.Visible = True
frmDGV.Show()
Trying to Fill the datatable shows exception 'No value given for one or more required parameters.'
The value of command.CommandText at that point is "Select Year from tblTest WHERE Year = #Year"
Your instance of OleDbDataAdapter was created using two parameters query text and connection.
Dim UserQuery As New OleDbDataAdapter(command.CommandText, conn)
In this case DataAdapter doesn't know about parameters at all.
Instead use constructor with paremeter of type OleDbCommand.
Dim UserQuery As New OleDbDataAdapter(command)
In your code instance of OleDbCommand already associated with connection