How to insert listview items into 3 different tables VB.net - 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.

Related

Insert text into MS access cells

i am begginer in visual basic and i want to insert text into cells in column in MS access but i doesn't find, how could i do that.
Here is code i tried:
Private Sub UpdateDataBase2()
provider = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source="
datafile = "F:\Test Database\Database.accdb"
conString = provider & datafile
myConnection.ConnectionString = conString
myConnection.Open()
Dim str As String
str = "Insert into TABLA([LABELS]) Values (?)"
Dim cmd As OleDbCommand = New OleDbCommand(str, myConnection)
cmd.Parameters.Add(New OleDbParameter("LABELS", CType(TextBox1.Text, String)))
Select Case panelCount
Case 1
' TextBox1.Text = cmd.Add("LABELS").Rows(0).Item(1).ToString()
Case 2
' str = "Insert into TABLA([LABELS]) Values (?)"
'cmd.Parameters.Add(New OleDbParameter("LABELS", CType(TextBox1.Text, String)))
End Select
Try
cmd.ExecuteNonQuery()
cmd.Dispose()
myConnection.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
myConnection.Close()
End Sub
In this application, i made a dynamics panels and labels.(dynamics is for me generated in code)
panelcount is variable which saves to another MS acces database count of dynamics panels. I want to save text from labels to database systematically(it means: text from label 1 insert to cell 1.), but every code i tried was not function for me.
I know i have to use loop, but first i want to try if code works.
Sorry for my english.
Any solution?
Database objects like Connection and Command should be declared in the method where they are used so they can be disposed.
Use Using...End Using blocks to ensure that your database objects are closed and disposed even if there is an error.
Insert creates a new record. If you want to Update an existing record you will need the primary key value for the record you want to update.
Dim Str = Update TABLA Set [LABELS] = ? Where ID = ?
Then you will need a second parameter.
cmd.Parameters.Add("ID", OleDbType.Integer).Value = intID
You will need to declare and provide a value for intID.
Don't show a message box while a connection is open.
Private Sub OPCode()
Try
Dim Str = "Insert into TABLA([LABELS]) Values (?)"
Dim ConStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=F:\Test Database\Database.accdb"
Using myConnection As New OleDbConnection(ConStr),
cmd As OleDbCommand = New OleDbCommand(Str, myConnection)
cmd.Parameters.Add("LABELS", OleDbType.VarChar).Value = TextBox1.Text
myConnection.Open()
cmd.ExecuteNonQuery()
End Using 'Closes and disposes the connection and disposes the command
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub

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

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

Insert selected records to another table in VB.Net and access

My name is Sarfaraz. I am developing a project in VB.Net and MSAccess 2007. I have a listbox control that is being populated from a table in Access called items. I am using a combination of two listbox's to select differnt values. I want to get the rate of the individual item when I hit the save button. The values are stored in a clients table. I am storing the data like Sugar=5 Biscuits=10 etc.
I am using a VB6 textbox and Recordset and need to know how I would implement the same thing in VB.Net
I have figured the answer but it is taking a very long time to perform the task and my system is going in a busy mode for almost 10 seconds. Is there anything wrong in this code Please have a look
Thank you.
Here is my code
Con.Open()
For l_index = 0 To ListBox2.Items.Count - 1
query = ("select Investigation.rate " & _
"from Investigation WHERE (((Investigation.Investigation) = '" & ListBox2.Items(l_index) & "'));")
Dim cmd2 As New OleDbCommand(query, Con)
'Con.Open()
Dim reader As OleDbDataReader = cmd2.ExecuteReader
reader.Read()
'Console.WriteLine(reader(0))
txtrate.Text = reader.GetString(0)
reader.Close()
'Con.Close()
' Con.Close()
'End If
Dim SqlString As String = "Insert Into patients (Receipt_No, OPD_MRD,Patientname,Investigation,Receipt_date,Receipt_time,rate) Values (?,?,?,?,?,?,?)"
Dim cmd As OleDbCommand = New OleDbCommand(SqlString, Con)
cmd.CommandType = CommandType.Text
cmd.Parameters.AddWithValue("Receipt_No", txtreceiptno.Text.Trim())
cmd.Parameters.AddWithValue("OPD_MRD", txtopd.Text.Trim())
cmd.Parameters.AddWithValue("Patientname", txtname.Text.Trim())
cmd.Parameters.AddWithValue("Investigation", CStr(ListBox2.Items(l_index)).ToString())
cmd.Parameters.AddWithValue("Receipt_date", lbldate.Text)
cmd.Parameters.AddWithValue("Receipt_time", lbltime.Text)
cmd.Parameters.AddWithValue("rate", txtrate.Text.Trim())
'Con.Open()
cmd.ExecuteNonQuery()
Next
Con.Close()

Update MS Access via vb.net

the below code runs without error, but the MS Access table isn't updating. What am I missing?
Try
cnn = New OleDbConnection(ConfigurationManager.ConnectionStrings("accConnectionString").ToString())
cnn.Open()
Catch ex As Exception
Debug.Print("Oops - no connection to database")
Exit Sub
End Try
Dim sql As String
sql = "SELECT * FROM tblSend WHERE UploadedSuccessfullyOn is null ORDER BY QueuedOn;"
Dim da As New OleDbDataAdapter(sql, cnn)
Dim ds As New DataSet
da.Fill(ds, "dsQueuedToSend")
For Each dr As DataRow In ds.Tables("dsQueuedToSend").Rows
' Perform other unrelated tasks in this space, removed for brevity
' If those other tasks were successful, update Access.
If success = True Then
sql = "UPDATE [tblSend] SET [UploadedSuccessfullyOn] = #uploadedOn WHERE (([UploadID]) = #uploadId);"
Dim cmd As OleDbCommand
cmd = New OleDbCommand(sql, cnn)
cmd.Parameters.Add("#uploadedOn", OleDbType.Date).Value = Now
cmd.Parameters.Add("#uploadedId", OleDbType.Integer).Value = dr("UploadID")
cmd.ExecuteNonQuery()
cmd.Dispose()
Console.WriteLine("Success: updated.")
Else
Console.WriteLine("Failed: Not updated.")
End If
Next
da.Dispose()
cnn.Close()
I've also tried with:
sql = "UPDATE [tblSend] SET [UploadedSuccessfullyOn] = ? WHERE (([UploadID]) = ?);"
Or simply add the values in the not-preferred/non-parameter approach:
sql = "UPDATE [tblSend] SET [UploadedSuccessfullyOn] = #" & Now & "# WHERE (([UploadID]) = " & dr("UploadID") & ");"
Dim cmd As OleDbCommand
cmd = New OleDbCommand(sql, cnn)
cmd.ExecuteNonQuery()
cmd.Dispose()
None of these approaches updates the MS Access table. Ideas? Thanks!
One thing I have been caught by before with Visual Studio is that when embedding an Access database in a WinForms project, when you run the project, the Access database is copied over from the original to the runtime directory, overwriting any changes you've made.
This can create the illusion that an update is not taking place, when in fact if you check at the right moment, it is.