Update edited ComboBox items in database instead of adding them - sql

I have a combobox named "Barcode", I fill it from database like this:
Sub fillIBarcode()
Barcode.DataSource = Nothing
Barcode.Items.Clear()
Dim adp As New SqlClient.SqlDataAdapter("Select distinct Barcode from Items where ItemCode=N'" & (ItemsDGV.CurrentRow.Cells(0).Value) & "'", SQlconn)
Dim ds As New DataSet
adp.Fill(ds)
Dim dt = ds.Tables(0)
'=====================================================
For I = 0 To dt.Rows.Count - 1
Barcode.Items.Add(dt.Rows(I).Item("Barcode"))
Barcode.SelectedIndex = 0
Next
End Sub
And it displays like that:
When the user edits and changes any numbers in the combobox and clicks the "Edit" button, how to submit this change and update the combobox items list immediately in the database?
I tried:
Private Sub Editbtn_Click(sender As Object, e As EventArgs) Handles Editbtn.Click
Dim cmdd As New SqlClient.SqlCommand
cmdd.Connection = SQlconn
cmdd.CommandText = "delete from Items where ItemCode=N'" & (ItemCode.Text) & "'"
cmdd.ExecuteNonQuery()
Dim sql = "select * From Items where ItemCode=N'" & (ItemCode.Text) & "'"
Dim adp As New SqlClient.SqlDataAdapter(sql, SQlconn)
Dim ds As New DataSet
adp.Fill(ds)
Dim dt = ds.Tables(0)
If dt.Rows.Count = 0 Then
For i = 0 To Barcode.Items.Count - 1
Dim dr = dt.NewRow
dr!ItemCode = ItemCode.Text
dr!Barcode = Barcode.Items(i).ToString
dt.Rows.Add(dr)
Next
Dim cmd As New SqlClient.SqlCommandBuilder(adp)
adp.Update(dt)
End If
End Sub
But it adds the new value, instead of updating the existing one.
I mean it added three barcodes, the original two, and the new edited one.

use SQL UPDATE QUERY :
you must conserve dt across form event to keep old value
dt has same index as combobox
declare dt as global in front of form code
Dim dt as datatable
in Sub fillIBarcode() remove DIM
dt = ds.Tables(0)
and in event handler execute an UPDATE query with ref to combobox selectedIndex:
Private Sub Editbtn_Click(sender As Object, e As EventArgs) Handles Editbtn.Click
Dim cmdd As New SqlClient.SqlCommand
cmdd.Connection = SQlconn
cmdd.CommandText = "UPDATE Items SET ItemCode=N'" & (ItemCode.Text) & "' WHERE ItemCode = N'" & dt.rows(Barcode.SelectedIndex).Item("Barcode") & "'"
cmdd.ExecuteNonQuery()
'update dt
dt.rows(Barcode.SelectedIndex).Item("Barcode") = ItemCode.Text
End Sub

Related

Data not showing up in DataGridView after a search query

Hello i am trying to search for data from a table using a funcion, however when i Input the number of the customerID it doesnt show up in the data gridview but the data is still passed to my textboxes. Could anyone help me in explaining what I did wrong?
Private Function SearchData(Fname As String, ID As Int32) As DataTable
Dim dt As New DataTable
Dim newds As New DataSet
Dim ssql As String = "SELECT * FROM customers WHERE fname LIKE #Fname OR CustomerID =#ID"
Using con As New SQLiteConnection(ConStr),
cmd As New SQLiteCommand(ssql, con)
con.Open()
cmd.Parameters.Add("#Fname", DbType.String).Value = Fname
cmd.Parameters.Add("#ID", DbType.Int32).Value = ID
dt.Load(cmd.ExecuteReader)
Dim da As New SQLiteDataAdapter(cmd)
da.Fill(newds, "customers")
dt = newds.Tables(0)
If dt.Rows.Count > 0 Then
ToTextbox(dt)
End If
dgvCustomerInfo.DataSource = dt
con.Close()
End Using
Return dt
End Function
Private Sub IbtnSearch_Click(sender As Object, e As EventArgs) Handles ibtnSearch.Click
If txtSearchName.Text <> "" Then
SearchData(txtSearchName.Text, "0")
Dim dt = GetSearchResults(txtSearchName.Text)
dgvCustomerInfo.DataSource = dt
ElseIf txtSearchID.Text <> "" Then
SearchData("0", txtSearchID.Text)
Dim dt = GetSearchResults(txtSearchID.Text)
dgvCustomerInfo.DataSource = dt
End If
End Sub
Try to think about what each line of code is doing. See in line comments
Private Function SearchData(Fname As String, ID As Int32) As DataTable
Dim dt As New DataTable
'Delete this line - there is no need for a Dataset
Dim newds As New DataSet
Dim ssql As String = "SELECT * FROM customers WHERE fname LIKE #Fname OR CustomerID =#ID"
Using con As New SQLiteConnection(ConStr),
cmd As New SQLiteCommand(ssql, con)
con.Open() 'Move this line - don't open the connection until directly before the .Execute...
'The Like operator would expect a pattern to match
'The interpolated string with the percent signs add wildcard characters
cmd.Parameters.Add("#Fname", DbType.String).Value = $"%{Fname}%"
cmd.Parameters.Add("#ID", DbType.Int32).Value = ID
dt.Load(cmd.ExecuteReader)
'Delete - We don't need a DataAdapter
Dim da As New SQLiteDataAdapter(cmd)
'Delete - We already have a filled DataTable
da.Fill(newds, "customers")
'Delete - same as above
dt = newds.Tables(0)
'Delete - Have no idea what this does. You are already going to display your data in a grid
If dt.Rows.Count > 0 Then
ToTextbox(dt)
End If
'Delete - You will set the DataSource in the User Interface code
dgvCustomerInfo.DataSource = dt
'Delete - End Using closes the connection and disposes the connection and command.
con.Close()
End Using
Return dt
End Function
The corrected code will look like this.
Private Function SearchData(Fname As String, ID As Int32) As DataTable
Dim dt As New DataTable
Dim ssql As String = "SELECT * FROM customers WHERE fname LIKE #Fname OR CustomerID =#ID"
Using con As New SQLiteConnection(ConStr),
cmd As New SQLiteCommand(ssql, con)
con.Open()
cmd.Parameters.Add("#Fname", DbType.String).Value = $"%{Fname}%"
cmd.Parameters.Add("#ID", DbType.Int32).Value = ID
dt.Load(cmd.ExecuteReader)
End Using
Return dt
End Function
In the user interface code I have added in line comments.
Private Sub IbtnSearch_Click(sender As Object, e As EventArgs) Handles ibtnSearch.Click
'Declare the DataTable outside the If block
'We do not need a New DataTable because SearchData is returning a DataTable
Dim dt As DataTable
If txtSearchName.Text <> "" Then
'Call only one function to return the DataTable
'SearchData is expecting 2 parameters, a String and an Integer
'Putting 0 in quotes makes it a String
dt = SearchData(txtSearchName.Text, 0)
'I removed the DataSource, Don't repeat yourself
'Assign it once after the If
ElseIf txtSearchID.Text <> "" Then
'The second argument must be an Integer, therefore the CInt()
dt = SearchData("", CInt(txtSearchID.Text))
Else
'Needed to add an Else to assign a value to dt if all else fails
dt = Nothing
End If
dgvCustomerInfo.DataSource = dt
End Sub

DataGridView is not displaying my delete button

I have a problem in my 2nd load of data using a DataGridView.
Here is my DataGridView and has a delete button when the data is first loaded:
On my 2nd load of data, this is the error I get:
After I click Ok, this is what happens in my DataGridView:
The delete button is gone.
This is my code:
Private Sub loaddata()
Dim con As New MySqlConnection
Dim cmd As New MySqlCommand
con.ConnectionString = "server=192.168.1.10;database=orderingsystem;username=server;password=server"
Dim da As New MySqlDataAdapter
Dim ds As New DataTable
Dim source As New BindingSource
Try
con.Open()
Dim query As String
Dim total As Double
Dim btn As New DataGridViewButtonColumn
btn.HeaderText = "Action"
btn.Text = "Delete"
btn.Name = "btn"
btn.UseColumnTextForButtonValue = True
query = "SELECT prodID, SUM(prodQty) as QTY, prodname as Name, prodPrice*SUM(prodQty) as Total from orderedlist where table_name = '" & Form1.Table_1.Name & "' GROUP BY prodID"
cmd = New MySqlCommand(query, con)
da.SelectCommand = cmd
da.Fill(ds)
source.DataSource = ds
dgv_myOrder.DataSource = ds
dgv_myOrder.Columns(0).Visible = False
For i As Integer = 0 To dgv_myOrder.Rows.Count - 1
total += Convert.ToDecimal(dgv_myOrder.Rows(i).Cells(3).Value).ToString("0.00")
Next
dgv_myOrder.Columns.Add(btn)
lbl_Total.Text = Decimal.Parse(total).ToString("0.00")
con.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
Finally
con.Dispose()
End Try
End Sub
Private Sub dgv_myOrder_CellClick(sender As Object, e As DataGridViewCellEventArgs) Handles dgv_myOrder.CellClick
If e.RowIndex = dgv_myOrder.NewRowIndex Or e.RowIndex < 0 Then
ElseIf e.ColumnIndex = dgv_myOrder.Columns("btn").Index Then
Dim connection As String = "server=192.168.1.10;database=orderingsystem;username=server;password=server;"
Dim con2 As New MySqlConnection(connection)
con2.Open()
Dim data As String = dgv_myOrder.SelectedRows(0).Cells(0).Value.ToString
Label2.Text = data
Dim rd2 As MySqlDataReader
Dim cmd2 As New MySqlCommand("UPDATE orderedlist SET cancelstatus = 1 WHERE prodID = '" & Label2.Text & "' and table_name = '" & Form1.Table_1.Name & "'", con2)
rd2 = cmd2.ExecuteReader
con2.Close()
con2.Open()
Dim rd3 As MySqlDataReader
Dim cmd3 As New MySqlCommand("UPDATE tableassistance SET cancellation = 1 WHERE table_name = '" & Form1.Table_1.Name & "'", con2)
rd3 = cmd3.ExecuteReader
MessageBox.Show("Wait for confirmation!", "System")
Me.Close()
Label2.Text = ""
End If
End Sub
I call loaddata() in my form load.
First remove this Line:
dgv_myOrder.Columns.Add(btn)
Don't add the button to datagridview inside code create it form the designer and use binding for other columns.
Steps :
1 . Create all your datagrdiview columns , using add columns button in the top right of the datagridview
this is how you add columns
2 .after you add the columns , bind every column to its related Column in database like this , you can get this window when you click on EditColumns in datagidview designer , change the DataPropertyName in the properties of each column change it to the name of the datatable column name that you want it to preview but not add it to the delete column button:
Binding the columns
3 . go to the properties of your delete button column in the datagridview you will find property called DefalutCellStyle inside it will find NullValue change it to "Delete".
Change the null value

datagridview not updating automatically in vb.net

The datagirdview is not updating after immediate in inserting records.
Private Sub updatedgv()
Using congv As OleDbConnection = New OleDbConnection("Provider=microsoft.jet.oledb.4.0;data source=..\library.mdb")
Dim strgv As String = "select * from NormalTransaction where RegNo='" & txt_RegisterNo.Text & "'"
Dim cmdgv As OleDbCommand = New OleDbCommand(strgv, congv)
Dim sdagv As OleDbDataAdapter = New OleDbDataAdapter(cmdgv)
Dim dsgv As DataSet = New DataSet("gvSet")
sdagv.Fill(dsgv)
DataGridView1.DataSource = dsgv
DataGridView1.DataMember = dsgv.Tables(0).TableName
End Using
End Sub
please help me to solve this.

Retrieve data from database according to multiple checked items from CheckedListBox

How to retrieve data from database according to multiple checked items from CheckedListBox? PlEASE GUIDE ME!!!
I'm currently doing a tutorial regarding to retrieve data from table according to multiple checked items from a CheckedListBox. Right now i'm able to retrieve data from table by only 1 checked item. how to make it retrievable by multiples checked item?
checklistbox1
checklistbox2
The tutorial will be: first load all related data into checklistbox1 as item, and user(s) may go and check the listed item, once the user checked particulars item(s) checklistbox2 will now query out data from another table where [field] = checked item(s) from checklistbox1.
load event as class
Public Sub Startload()
Dim connection As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source='" & aaa & "';Persist Security Info=False;")
Dim dt1 As New DataTable
Dim sqlstr As String = "SELECT * FROM tbl"
Dim command As New OleDbCommand(sqlstr, connection)
Dim adpt As New OleDbDataAdapter(command)
adpt.SelectCommand = command
adpt.Fill(dt1)
CheckedListBox1.DisplayMember = "name"
CheckedListBox1.ValueMember = "ID"
CheckedListBox1.DataSource = dt1
End Sub
when Checked change execute checkedload()
Private Sub CheckedListBox1_ItemCheck(ByVal sender As Object, ByVal e As System.Windows.Forms.ItemCheckEventArgs) Handles CheckedListBox1.ItemCheck
Label1.Text = CheckedListBox1.SelectedValue
checkedload()
End Sub
After checked items from checklistbox1 (checkedload) will execute and retrieves data and show in checklistbox2
Private Sub checkedload()
Dim x As String = Label1.Text
Dim connection As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source='" & aaa & "';Persist Security Info=False;")
Dim dt2 As New DataTable
Dim sqlstr2 As String = "SELECT * FROM tbl2 WHERE [name]='" & x & "'"
Dim command2 As New OleDbCommand(sqlstr2, connection)
Dim adpt2 As New OleDbDataAdapter(command2)
adpt2.SelectCommand = command2
adpt2.Fill(dt2)
CheckedListBox2.DisplayMember = "namex"
CheckedListBox2.ValueMember = "ID"
CheckedListBox2.DataSource = dt2
End Sub
Self Solved
Dim i As Integer
Dim connection As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source='" & aaa & "';Persist Security Info=False;")
Dim dt2 As New DataTable
For i = 0 To CheckedListBox1.Items.Count - 1 Step i + 1
If CheckedListBox1.GetItemCheckState(i) = CheckState.Checked Then
Dim xx As String = (CType(CheckedListBox1.Items(i), DataRowView))("name")
Dim sqlstr2 As String = "SELECT * FROM tbl2 WHERE [name]='" & xx & "'"
Dim command2 As New OleDbCommand(sqlstr2, connection)
Dim adpt2 As New OleDbDataAdapter(command2)
adpt2.SelectCommand = command2
adpt2.Fill(dt2)
CheckedListBox2.DisplayMember = "namex"
CheckedListBox2.ValueMember = "ID"
CheckedListBox2.DataSource = dt2
End If
Next
Private Sub CheckedListBox1_ItemCheck(ByVal sender As Object, ByVal e As System.Windows.Forms.ItemCheckEventArgs) Handles CheckedListBox1.ItemCheck
Dim i as Integer=0
For Each li as ListItem in CheckedListBox1.Items
If li.Selected=True Then
Dim lab As New Label
lab.ID="lab" & i
lab.Text=li.SelectedItem.Value
i += 1
End If
Next
hiddenfield1.Value=i 'hidden field
checkedload()
End Sub
Private Sub checkedload()
For i as Integer = o To hiddenField1.Value
Dim x As String = Request.Form("lab" & i)
Dim connection As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source='" & aaa & "';Persist Security Info=False;")
Dim dt2 As New DataTable
Dim sqlstr2 As String = "SELECT * FROM tbl2 WHERE [name]='" & x & "'"
Dim command2 As New OleDbCommand(sqlstr2, connection)
Dim adpt2 As New OleDbDataAdapter(command2)
adpt2.SelectCommand = command2
adpt2.Fill(dt2)
CheckedListBox2.DisplayMember = "namex"
CheckedListBox2.ValueMember = "ID"
CheckedListBox2.DataSource = dt2
Next
End Sub
I haven't checked it anyway. but it could help you

Update a Single cell of a database table in VB.net

I am using MS Access Database. Now I have to update a particular cell value. Here is my code:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim str As String
Dim Presc As New System.Text.StringBuilder
Dim prs As String(), j As Integer
prs = Split(txtPrescription.Text, vbCrLf)
For j = 0 To prs.Length - 1
Presc.Append(prs(j))
Presc.Append(",")
Next
Try
str = Trim(lsvCase.SelectedItems(0).Text)
'MessageBox.Show(str)
Dim con As System.Data.OleDb.OleDbConnection
Dim ds As New DataSet
Dim rea As System.Data.OleDb.OleDbDataReader
con = New OleDb.OleDbConnection
Dim da As New System.Data.OleDb.OleDbDataAdapter
con.ConnectionString = "Provider = Microsoft.ACE.OLEDB.12.0; Data Source= F:\Sowmya Laptop Backups\sowdb1.accdb;"
con.Open()
Dim cmd As OleDb.OleDbCommand = con.CreateCommand
cmd.CommandText = "UPDATE Casehistory set Prescription =' " & Presc.ToString() & "'"
rea = cmd.ExecuteReader
cmd.ExecuteNonQuery()
da.FillSchema(ds, SchemaType.Mapped)
da.Update(ds, "Casehistory")
con.Close()
Catch ex As Exception
Finally
End Try
End Sub
This code updates all the cells in that column. I want to update only the particular cell having Case_ID = str
Where I have to add the WHERE clause (WHERE Case_ID = " & str & "
I would use command parameters, neater and prevents the SQL injection issue. Something like:
cmd.CommandText = "UPDATE Casehistory set Prescription =#Presc WHERE Case_ID = #CaseID"
cmd.Parameters.AddWithValue("#Presc", Presc.ToString())
cmd.Parameters.AddWithValue("#CaseID",str)
As an aside, having all this code in the button click event is less than ideal. You might want to investigate structuring your app in a more maintainable way - perhaps with a Data Layer for example.
The Where clause should be appended to the end of the OleDbCommmand.CommandText, where you define the Update statement.