Using 2 combo boxes to populate a datagridview in VB.NET - vb.net

I having problems understanding why my one of my comboboxes displays a filtered search but the other one doesn't, I am using the same code for both comboboxes but modified some SQL queries linked to my database. I have also noticed that when I remove or comment out the code for any one of the comboboxes the the filtered search happens for the one hasn't been commented or removed. I also used an "If, Else" statement but still doesn't work. I would also want for both comboboxes to be used to filter a datagridview. Just to keep in mind once the item is selected from the combobox a search button is pressed to filer/display data into the datagridview.
Kind Regards
Here is my code and form:
[Redundant Data being displayed] https://i.stack.imgur.com/JEQI4.png
[ComboBox Brand works as intended] https://i.stack.imgur.com/6YyBf.png
[ComboBox Category displays everything rather than displaying the category chosen] https://i.stack.imgur.com/oEfII.png
Private Sub BtnSearch_Click(sender As Object, e As EventArgs) Handles BtnSearch.Click
If Not CmbBrand.SelectedIndex & CmbCategory.SelectedIndex = Nothing Then
BrandDisplay()
ElseIf CmbBrand.SelectedIndex & Not CmbCategory.SelectedIndex = Nothing Then
CategoryDisplay()
ElseIf Not CmbBrand.SelectedIndex & Not CmbCategory.SelectedIndex = Nothing Then
If DbConnect() Then
DgvRecord.Rows.Clear()
Dim SQLCmd As New OleDbCommand
With SQLCmd
.Connection = cn
.CommandText = "Select * " &
"From TblStock " &
"Where STCategory Like #CategorySearch"
.Parameters.AddWithValue("#CategorySearch", "%" & CmbCategory.Text & "%")
Dim rs As OleDbDataReader = .ExecuteReader()
SQLCmd.ExecuteReader()
While rs.Read
Dim NewStockRow As New DataGridViewRow()
NewStockRow.CreateCells(DgvRecord)
NewStockRow.SetValues({rs("StockID"), rs("STDateTime"), rs("STCategory"), rs("STBrand"), rs("STItemDescription"), rs("STSerialNumber"), rs("StockIn"), rs("StockOut"), rs("Stock")})
NewStockRow.Tag = rs("StockID")
DgvRecord.Rows.Add(NewStockRow)
End While
rs.Close()
If DgvRecord.Rows(0).Selected = True Then
MessageBox.Show("Please select a Category from the drop down list", "Category", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
End If
End With
End If
End If
cn.Close()
End Sub
Private Sub BrandDisplay()
If DbConnect() Then
DgvRecord.Rows.Clear()
Dim SQLCmd As New OleDbCommand
With SQLCmd
.Connection = cn
.CommandText = "Select * " &
"From TblStock " &
"Where STBrand Like #BrandSearch"
.Parameters.AddWithValue("#BrandSearch", "%" & CmbBrand.Text & "%")
Dim rs As OleDbDataReader = .ExecuteReader()
SQLCmd.ExecuteReader()
While rs.Read
Dim NewStockRow As New DataGridViewRow()
NewStockRow.CreateCells(DgvRecord)
NewStockRow.SetValues({rs("StockID"), rs("STDateTime"), rs("STCategory"), rs("STBrand"), rs("STItemDescription"), rs("STSerialNumber"), rs("StockIn"), rs("StockOut"), rs("Stock")})
NewStockRow.Tag = rs("StockID")
DgvRecord.Rows.Add(NewStockRow)
End While
rs.Close()
If DgvRecord.Rows(0).Selected = True Then
MessageBox.Show("Please select a Brand from the drop down list", "Brand", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
End If
End With
End If
cn.Close()
End Sub
Private Sub CategoryDisplay()
If DbConnect() Then
DgvRecord.Rows.Clear()
Dim SQLCmd As New OleDbCommand
With SQLCmd
.Connection = cn
.CommandText = "Select * " &
"From TblStock " &
"Where STCategory Like #CategorySearch"
.Parameters.AddWithValue("#CategorySearch", "%" & CmbCategory.Text & "%")
Dim rs As OleDbDataReader = .ExecuteReader()
SQLCmd.ExecuteReader()
While rs.Read
Dim NewStockRow As New DataGridViewRow()
NewStockRow.CreateCells(DgvRecord)
NewStockRow.SetValues({rs("StockID"), rs("STDateTime"), rs("STCategory"), rs("STBrand"), rs("STItemDescription"), rs("STSerialNumber"), rs("StockIn"), rs("StockOut"), rs("Stock")})
NewStockRow.Tag = rs("StockID")
DgvRecord.Rows.Add(NewStockRow)
End While
rs.Close()
If DgvRecord.Rows(0).Selected = True Then
MessageBox.Show("Please select a Category from the drop down list", "Category", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
End If
End With
End If
cn.Close()
End Sub
```

It is a good idea to separate your User Interface code from you database code. Your event procedure code should be rather brief.
Declare your Connections, Commands and DataReaders in the method where they are used so they can be disposed. Using...End Using blocks do this for us; they also close the connection. Pass your connection string directly to the constructor of the connection.
We have a different CommandText and ParametersCollection for each possibility. For Sql Server use the Add method rather than AddWithValue.
Private Sub BtnSearch_Click(sender As Object, e As EventArgs) Handles BtnSearch.Click
Dim dt = GetSearchData(CmbBrand.Text, CmbCategory.Text)
DGVRecord.DataSource = dt
End Sub
Private Function GetSearchData(Brand As String, Category As String) As DataTable
Dim dt As New DataTable
Dim sqlString = "Select * From From TblStock "
Using cn As New SqlConnection("Your connection string"),
cmd As New SqlCommand()
cmd.Connection = cn
If Not String.IsNullOrEmpty(Brand) AndAlso Not String.IsNullOrEmpty(Category) Then
cmd.CommandText = sqlString & "Where STCategory = #CategorySearch And STBrand = #BrandSearch;"
cmd.Parameters.Add("#CategorySearch", SqlDbType.VarChar).Value = Brand
cmd.Parameters.Add("#BrandSearch", SqlDbType.VarChar).Value = Category
ElseIf Not String.IsNullOrEmpty(Brand) Then
cmd.CommandText = sqlString & "Where STBrand = #BrandSearch;"
cmd.Parameters.Add("#BrandSearch", SqlDbType.VarChar).Value = Category
ElseIf Not String.IsNullOrEmpty(Category) Then
cmd.CommandText = sqlString & "Where STCategory = #CategorySearch;"
cmd.Parameters.Add("#CategorySearch", SqlDbType.VarChar).Value = Brand
Else
cmd.CommandText = sqlString & ";"
End If
cn.Open()
Using reader = cmd.ExecuteReader()
dt.Load(reader)
End Using
End Using
Return dt
End Function

For better understanding you need to change those first "if... then... else...".
If the combobox is not selected it will have value -1 so you can do it like this:
Dim bBrandIsSelected as boolean = CmbBrand.SelectedIndex <> -1
Dim bCategoryIsSelected as boolean = CmbCategory.SelectedIndex <> -1
Now you can build the code more easily like:
If bBrandIsSelected AndAlso bCategoryIsSelected then
' do something
else
if bBrandIsSelected then
BrandDisplay()
else
if bCategoryIsSelected then
CategoryDisplay()
End if
End if
End if

Related

Database locked in vb.net when trying to update data in vb.net

Hello I have a simple method to update customer details in one of my database tables however when i try to update it an error occurs saying the database is locked. I have no idea how to fix this because my add and delete queries work just fine.
This is the error message:
System.Data.SQLite.SQLiteException: 'database is locked
database is locked'
Public Sub updateguest(ByVal sql As String)
Try
con.Open()
With cmd
.CommandText = sql
.Connection = con
End With
result = cmd.ExecuteNonQuery
If result > 0 Then
MsgBox("NEW RECORD HAS BEEN UPDATED!")
con.Close()
Else
MsgBox("NO RECORD HASS BEEN UPDATDD!")
End If
Catch ex As Exception
MsgBox(ex.Message)
Finally
con.Close()
End Try
End Sub
Private Sub IbtnUpdate_Click(sender As Object, e As EventArgs) Handles ibtnUpdate.Click
Dim usql As String = "UPDATE Customers SET fname = '" & txtFName.Text & "'" & "WHERE CustomerID ='" & txtSearchID.Text & "'"
updateguest(usql)
End Sub
Private Sub IbtnSearch_Click(sender As Object, e As EventArgs) Handles ibtnSearch.Click
Dim sSQL As String
Dim newds As New DataSet
Dim newdt As New DataTable
Dim msql, msql1 As String
Dim con As New SQLiteConnection(ConnectionString)
con.Open()
msql = "SELECT * FROM Customers Where Fname Like '" & txtSearchName.Text & "%'"
msql1 = "SELECT * FROM Customers Where CustomerID '" & txtSearchID.Text & "'"
Dim cmd As New SQLiteCommand(msql, con)
Dim cmd1 As New SQLiteCommand(msql1, con)
Dim dt = GetSearchResults(txtSearchName.Text)
dgvCustomerInfo.DataSource = dt
Dim mdr As SQLiteDataReader = cmd.ExecuteReader()
If mdr.Read() Then
If txtSearchName.Text <> "" Then
sSQL = "SELECT * FROM customers WHERE fname LIKE'" & txtSearchName.Text & "%'"
Dim con1 As New SQLiteConnection(ConnectionString)
Dim cmd2 As New SQLiteCommand(sSQL, con1)
con1.Open()
Dim da As New SQLiteDataAdapter(cmd2)
da.Fill(newds, "customers")
newdt = newds.Tables(0)
If newdt.Rows.Count > 0 Then
ToTextbox(newdt)
End If
dgvCustomerInfo.DataSource = newdt
con1.Close()
txtSearchID.Clear()
ElseIf txtSearchID.Text <> "" Then
sSQL = "SELECT * FROM customers WHERE CustomerID ='" & txtSearchID.Text & "'"
Dim con2 As New SQLiteConnection(ConnectionString)
Dim cmd2 As New SQLiteCommand(sSQL, con2)
con2.Open()
Dim da As New SQLiteDataAdapter(cmd2)
da.Fill(newds, "customers")
newdt = newds.Tables(0)
If newdt.Rows.Count > 0 Then
ToTextbox(newdt)
End If
dgvCustomerInfo.DataSource = newdt
con2.Close()
txtSearchName.Clear()
End If
Else
MsgBox("No data found")
End If
End Sub
Private Sub IbtnDelete_Click(sender As Object, e As EventArgs) Handles ibtnDelete.Click
Dim dsql As String = "DELETE FROM customers WHERE customerid = " & txtSearchID.Text & ""
deleteme(dsql)
updatedgv(dgvCustomerInfo)
txtSearchID.Clear()
txtSearchName.Clear()
End Sub
Public Sub deleteme(ByVal sql As String)
Try
con.Open()
With cmd
.CommandText = sql
.Connection = con
End With
result = cmd.ExecuteNonQuery
If result > 0 Then
MsgBox("NEW RECORD HAS BEEN DELTED!")
con.Close()
Else
MsgBox("NO RECORD HASS BEEN DELTED!")
End If
Catch ex As Exception
MsgBox(ex.Message)
Finally
con.Close()
End Try
End Sub
You made a good start on keeping your database code separate from you user interface code. However, any message boxes should be shown in the user interface and any sql statements should be written in the data access code.
I used Using...End Using blocks to ensure that database objects are closed and disposed. I used parameters to protect against sql injection. I am not too sure of the mapping of DbType types to Sqlite types. You might have to fool with that a bit. In you original Update statement you had the ID value in quotes. This would pass a string. When you use parameters, you don't have to worry about that or ampersands and double quotes. Just one clean string.
Private ConStr As String = "Your connection string"
Public Function updateguest(FirstName As String, ID As Integer) As Integer
Dim Result As Integer
Dim usql As String = "UPDATE Customers SET fname = #fname WHERE CustomerID = #ID;"
Using con As New SQLiteConnection(ConStr),
cmd As New SQLiteCommand(usql, con)
cmd.Parameters.Add("#fname", DbType.String).Value = FirstName
cmd.Parameters.Add("#ID", DbType.Int32).Value = ID
con.Open()
Result = cmd.ExecuteNonQuery
End Using
Return Result
End Function
Private Sub IbtnUpdate_Click(sender As Object, e As EventArgs) Handles ibtnUpdate.Click
Try
Dim Result = updateguest(txtFName.Text, CInt(txtSearchID.Text))
If Result > 0 Then
MsgBox("New RECORD HAS BEEN UPDATED!")
Else
MsgBox("NO RECORD HAS BEEN UPDATDD!")
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub

Dynamic Sql - retrieve from Oracle

I have a form with button which should find records from Oracle database. I have three Textboxes on same form, and If text matches with values in fields of DB, Datagrid should show me this records. Here is my code:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
'connect to oracle DB
Dim oradb As String = "Data Source=orcl;User Id=Lucky;Password=Example;"
Dim conn As New OracleConnection(oradb)
conn.Open()
Dim SQL As String
SQL = "SELECT * FROM MyTable WHERE 1=1"
'SQL statement for 1st textbox
If Not TxtName.Text = "" Then
SQL = SQL & " AND USER_NAME =" & TxtName.Text
End If
'SQL statement for 2nd textbox
If Not TxtSurname.Text = "" Then
SQL = SQL & " AND USER_SURNAME =" & TxtSurname.Text
End If
'SQL statement for 3rd textbox
If Not TxtAddress.Text = "" Then
SQL = SQL & " AND USER_ADDRESS=" & TxtAddress.Text
End If
'select SQL statements and retrieve data using ExecuteReader
Dim cmd As New OracleCommand(SQL, conn)
cmd.CommandType = CommandType.Text
Dim dr As OracleDataReader = cmd.ExecuteReader()
Dim dt As New DataTable
dt.Load(dr)
DataGridView1.DataSource = dt
End Sub
What am I doing wrong, nothing happens when button clicked?
This is a non-tested sample of the direction you could try:
Private Sub populateDataGridView()
'connect to oracle DB
Const connectionString As String = "Data Source=orcl;User Id=Lucky;Password=Example;"
Using conn As New OracleConnection(connectionString)
conn.Open()
Using cmd As New OracleCommand()
Dim SQL As String = "SELECT * FROM testtable "
Dim conjunction As String = " Where "
'SQL statement for 1st textbox
If Not TxtName.Text.Length = 0 Then
SQL = String.Concat(SQL, conjunction, " USER_NAME like :username")
cmd.Parameters.Add(New OracleParameter("username", String.Concat("%", TxtName.Text, "%")))
conjunction = " and "
End If
'SQL statement for 2nd textbox
If Not TxtSurname.Text.Length = 0 Then
SQL = String.Concat(SQL, conjunction, " user_surname like :usersurname")
cmd.Parameters.Add(New OracleParameter("usersurname", String.Concat("%", TxtSurname2.Text, "%")))
conjunction = " and "
End If
'SQL statement for 3rd textbox
If Not TxtAddress.Text.Length = 0 Then
SQL = String.Concat(SQL, conjunction, " user_address like :useraddress")
cmd.Parameters.Add(New OracleParameter("useraddress", String.Concat("%", TxtAddress.Text, "%")))
End If
'select SQL statements and retrieve data using ExecuteReader
cmd.Connection = conn
cmd.CommandText = SQL
cmd.CommandType = CommandType.Text
Dim dr As OracleDataReader = cmd.ExecuteReader()
Dim dt As New DataTable
dt.Load(dr)
DataGridView1.DataSource = dt
End Using
End Using
End Sub

How to compare a combo box value with a table value stored in SQL Server

I am trying to compare a combobox value with data stored already in database, if data doesn't exist then user should be informed that he should select a record from the list or write down the name which already exist in database!
Below is the code I have written for it:
Private Sub btnsave_Click(sender As Object, e As EventArgs) Handles btnsave.Click
Try
'Declare new data adapter and new datatable for publisher id & Auhtor id and ISBN
' to check record exist already or no
Dim pda As New SqlDataAdapter
Dim pdt As DataTable
Dim matchPub_name As String = cboPub_id.Text
pda = New SqlDataAdapter("SELECT pub_name FROM publisher WHERE pub_name =#pub_name", cn)
pdt = New DataTable
pda.Fill(pdt)
Dim ada As New SqlDataAdapter
Dim adt As DataTable
Dim matchAuthor_name As String = cboAuthor_id.Text
ada = New SqlDataAdapter("SELECT author_name FROM author WHERE author_name =" & matchAuthor_name, cn)
adt = New DataTable
ada.Fill(adt)
Dim matchISBN As String = txtisbn.Text.ToString
da = New SqlDataAdapter("SELECT isbn from book WHERE isbn =" & "'" & matchISBN & "'", cn)
dt = New DataTable
da.Fill(dt)
If pdt.Rows.Count = -1 Then
lblAlert.BackColor = Color.HotPink
ErrorProvider1.SetError(cboPub_id, _
"*Please Select or type available Publishers or register new in Publisher form")
lblAlert.Text = "Check Respected Error"
lblInfo.Text = ""
ElseIf adt.Rows.Count = -1 Then
lblAlert.BackColor = Color.HotPink
ErrorProvider1.SetError(cboAuthor_id, _
"*Please Select or type available Authors or register new in Author form")
lblAlert.Text = "Check Respected Error"
lblInfo.Text = ""
ElseIf dt.Rows.Count > 0 Then
lblAlert.BackColor = Color.HotPink
ErrorProvider1.SetError(cboAuthor_id, _
"*a record with provided ISBN already exist in Database. Insert Unique ISBN")
lblAlert.Text = "Check Respected Error"
lblInfo.Text = ""
Else
'Insert into Book Table
cmd = New SqlCommand("Insert into book(isbn, book_name, price, rack_no, no_of_books, staff_id, " _
& " pub_id, sub_code, author_id) values(#isbn, #book_name, #price, #rack_no, " _
& " #no_of_books, #staff_id, #pub_id, #sub_code, #author_id)", cn)
With cmd.Parameters
.AddWithValue("#isbn", txtisbn.Text).ToString()
.AddWithValue("#book_name", txtbook_name.Text)
.AddWithValue("#price", txtprice.Text)
.AddWithValue("#rack_no", txtrack_no.Text)
.AddWithValue("#no_of_books", TxtNo_of_Books.Text)
.AddWithValue("#staff_id", Convert.ToInt32(cboStaff_id.SelectedValue.ToString()))
.AddWithValue("#pub_id", Convert.ToInt32(cboPub_id.SelectedValue.ToString()))
.AddWithValue("#sub_code", cboSub_Code.Text)
.AddWithValue("#author_id", cboAuthor_id.SelectedValue)
End With
cmd.ExecuteNonQuery()
'Insert into Published_by Table
cmd = New SqlCommand("Insert into published_by(isbn, pub_id, pub_date, vol_no) " _
& " values(#isbn, #pub_id, #pub_date, #vol_no)", cn)
cmd.Parameters.AddWithValue("#isbn", txtisbn.Text).ToString()
cmd.Parameters.AddWithValue("#pub_id", Convert.ToInt32(cboPub_id.SelectedValue.ToString()))
cmd.Parameters.AddWithValue("#pub_date", DateTimePicker1.Text)
cmd.Parameters.AddWithValue("#vol_no", txtvol_no.Text)
cmd.ExecuteNonQuery()
'Insert into Authored_by Table
cmd = New SqlCommand("Insert into authored_by(isbn, author_id, completion_date) " _
& " values(#isbn, #author_id, #completion_date)", cn)
cmd.Parameters.AddWithValue("#isbn", txtisbn.Text).ToString()
cmd.Parameters.AddWithValue("#author_id", cboAuthor_id.SelectedValue)
cmd.Parameters.AddWithValue("#completion_date", dtpCompletion_Date.Text)
cmd.ExecuteNonQuery()
'MessageBox.Show("Record Saved Successfully", "Save", MessageBoxButtons.OK, MessageBoxIcon.Information)
lblAlert.Text = ""
lblInfo.Text = "Saved"
End If
Catch ex As Exception
MessageBox.Show("Not Completed Because OF The Following Error " & "%" & ex.Message & "%", "Error", _
' MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
but when I am entering data in cboAuthor_Name which is not available in DB it gives error Invalid column name ' '
how to handle this? any help?
There are a couple of problems in your code. The worst one is the string concatenation to build an sql query. Then there is a lesser one in using an SqlDataAdapter filling a DataTable only to discover if a record exists or not.
You could change your code to
Private Sub btnsave_Click(sender As Object, e As EventArgs) Handles btnsave.Click
Dim matchPub_name As String = cboPub_name.Text
Dim matchAuthor_name As String = cboAuthor_id.Text
Dim matchISBN As String = txtisbn.Text.ToString
Using conn = new SqlConnection(....constring here ....)
Using cmd = new SqlCommand("SELECT pub_name FROM publisher WHERE pub_name = #name", conn)
conn.Open
cmd.Parameters.Add("#name", SqlDbType.NVarChar).Value = matchPub_name
Dim publisherName = cmd.ExecuteScalar()
if publisherName is Nothing Then
lblAlert.BackColor = Color.HotPink
ErrorProvider1.SetError(cboPub_name, _
"*Please Select .....")
lblAlert.Text = "Check Respected Error"
lblInfo.Text = ""
Return
End If
cmd.CommandText = "SELECT author_name FROM author WHERE author_name = #name"
cmd.Parameters("#name").Value = matchAuthor_name
Dim authorName = cmd.ExecuteScalar()
if authorName is Nothing Then
lblAlert.BackColor = Color.HotPink
ErrorProvider1.SetError(cboAuthor_name, _
"*Please Select .....")
lblAlert.Text = "Check Respected Error"
lblInfo.Text = ""
Return
End If
cmd.CommandText = "SELECT isbn from book WHERE isbn = #name"
cmd.Parameters("#name").Value = matchISBN
Dim isbnCode = cmd.ExecuteScalar()
if isbnCode IsNot Nothing Then
lblAlert.BackColor = Color.HotPink
ErrorProvider1.SetError(txtISBN, _
"*ISBN Exists .....")
lblAlert.Text = "Check Respected Error"
lblInfo.Text = ""
Return
End If
' Now insert into Book Table '
End Using
End Using
End Sub
Using parameters is the correct way to pass values to your database instead of building a text that is subject to parsing problems (your original code misses the single quote around the name) and Sql Injection attacks. Using directly a command with ExecuteScalar doesn't require to build a datatable. ExecuteScalar returns the first column of the first row, if any, otherwise the return is nothing.
Notice also that I don't use a global connection object but build one on the spot and destroy it through the Using block. There is a mechanism called Connection Pooling that allow objects like a Connection to be rebuilt very easily and quickly.
con.Open();
SqlCommand cmd = new SqlCommand("sp_Addbookdetails", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#class", ddlclass.SelectedValue.ToString());
cmd.Parameters.AddWithValue("#Booktype", txtbktype.Text);
cmd.Parameters.AddWithValue("#Quantity", Convert.ToInt32(txtqty.Text));
cmd.Parameters.AddWithValue("#price", Convert.ToInt32(txtPrice.Text));

Insert multiple data into a single cell SQLyog vb.net

I am trying to develop a management system for dentists, this the system i am developing
THIS MY PROGRAM'S SCREENSHOT
when the dentist inputted a data on a textbox, it will be saved on the database and whenever the dentist insert a data again on that textbox, instead of replacing the older data with a newer data, it will store the data, making the cell store multiple data
and this is my code for adding data into the table
table name: teethhistory
database name: PatientManagementSystem
Private Sub txtURThirdMolar_KeyDown(sender As Object, e As KeyEventArgs) Handles txtURThirdMolar.KeyDown
If e.KeyCode = Keys.Enter Then
MySqlConn.Open()
query1 = "SELECT * FROM teethhistory WHERE Patient_ID_Number ='" & lblID.Text & "'"
cmd1 = New MySqlCommand(query1, MySqlConn)
reader = cmd1.ExecuteReader
If reader.HasRows Then
Dim i As Integer
With cmd
.Connection = MySqlConn
.CommandText = "UPDATE teethhistory SET Up_Right_3rd_Molar ='" & txtURThirdMolar.Text & "' WHERE Patient_ID_Number = " & lblID.Text
reader.Close()
i = .ExecuteNonQuery
End With
If i > 0 Then
MsgBox("Updated!", MsgBoxStyle.Information, "Success")
Else
MsgBox("Failed", MsgBoxStyle.Information, "Failed")
End If
Else
Dim cmd As MySqlCommand = MySqlConn.CreateCommand
cmd.CommandText = String.Format("INSERT INTO teethhistory (Patient_ID_Number, Fullname, Up_Right_3rd_Molar )" &
"VALUES ('{0}' ,'{1}' ,'{2}')",
lblID.Text,
lblFullname.Text,
txtURThirdMolar.Text)
reader.close()
Dim affectedrows As Integer = cmd.ExecuteNonQuery()
If affectedrows > 0 Then
MsgBox("Saved!", MsgBoxStyle.Information, "Success")
Else
MsgBox("Saving failed.", MsgBoxStyle.Critical, "Failed")
End If
MySqlConn.close()
End If
End Sub
if you want to Append the Existing text In field with new data from textbox,use Update command as
.CommandText = "UPDATE teethhistory SET Up_Right_3rd_Molar = concat('" & txtURThirdMolar.Text & "',Up_Right_3rd_Molar) WHERE Patient_ID_Number = " & lblID.Text
for inserting values seperated by commas, just insert a comma before the string ion concat function.
hope i undestood your problem well and this solves it.

Parameterizing sql in vb

I have this module call Procedure , and I want to parametrize it. I'm sending a string as the query to the procedure module . I look already in google but I could not find the answer to my problem.
Procedures.Insert("INSERT INTO Technician (tec_name, tec_email, rol_id) VALUES ('" & txt_tech.text & "', '" & txt_tech_email.text & "', " & cbo_tech_role.selectvalue.tostring & ")", "Technican Add Correct")
========================================
I will probably change it for .....
Procedures.Insert("INSERT INTO Technician (tec_name, tec_email, rol_id) VALUES ('#tech_name', '#tech_email', '#tech_role' ")", "Technican Add Correct")
================ But I dont know where I can Parametrized
Public Sub Insert(query As String, msg As String)
Dim cn As New SqlConnection(cs)
Dim cmd As New SqlCommand
Try
cn.Open()
With cmd
.CommandType = CommandType.Text
.CommandText = query
.Connection = cn
.Parameters.AddValueWith("#tech_name",txt_tech_name.text)
.Parameters.AddValueWith("#tech_email",txt_tech_email.text)
.Parameters.AddValueWith("#tech_rol",txt_tech_role.selectValue.tostring)
.ExecuteNonQuery()
End With
MessageBox.Show(msg, "INSERT", MessageBoxButtons.OK, MessageBoxIcon.Information)
Catch ex As Exception
MessageBox.Show(ex.Message.ToString, ". : : ERROR : : .", MessageBoxButtons.OK, MessageBoxIcon.Error)
Finally
If cn IsNot Nothing AndAlso cn.State <> ConnectionState.Closed Then
cn.Close()
cn = Nothing
End If
End Try
End Sub
Because I have a module that is separate from the main code , I'm not able to call the textboxes because they are separate from the main module ... any idea on how to do this ?? ... Dont be hard .. This is my 14 week working with VB.. :/
Add to the Insert function parameter for SqlParameters
Public Sub Insert(query As String, msg As String, params As SqlParameter())
Dim cn As New SqlConnection(cs)
Dim cmd As New SqlCommand
Try
cn.Open()
With cmd
.CommandType = CommandType.Text
.CommandText = query
.Connection = cn
If params IsNot Nothing AndAlso params.Count > 0 Then
.Parameters.AddRange(params)
End If
.ExecuteNonQuery()
End With
MessageBox.Show(msg,
"INSERT",
MessageBoxButtons.OK,
MessageBoxIcon.Information)
Catch ex As Exception
MessageBox.Show(ex.Message.ToString, ". : : ERROR : : .",
MessageBoxButtons.OK,
MessageBoxIcon.Error)
Finally
If cn IsNot Nothing AndAlso cn.State <> ConnectionState.Closed Then
cn.Close()
cn = Nothing
End If
End Try
End Sub
Then use it like this:
Dim query As String = "INSERT INTO Technician (tec_name, tec_email, rol_id) VALUES (#tech_name, #tech_email, #tech_role)"
Dim msg As String = "Technican Add Correct"
Dim params As SqlParameter() = {New SqlParameter("#tech_name",txt_tech_name.text),
New SqlParameter("#tech_email",txt_tech_email.text),
New SqlParameter("#tech_rol",txt_tech_role.selectValue.tostring)}
Procedures.Insert(query, msg, params)
Using array of SqlParameter give you a possibility for using same function with parameter type other then string
You can have it this way... it works for me.
String query = "INSERT INTO Technician(tec_name, tec_email, rol_id) VALUES(#tech_name, #tech_email, #tech_rolr)"
params = {"tech_name", "tech_email", "tech_rolr"}
values = {"" & txt_tech_name.text, "" & txt_tech_email.text, "" & txt_tech_role.selectValue.tostring()}
SaveUpdateDelete(query, params, values)
under module, you can put this
Public params() As String
Public values() As String
Public Sub SaveUpdateDelete(ByVal sql As String, ByVal parameters() As String, ByVal Values() As String)
If con.State = ConnectionState.Open Then
con.Close()
End If
con.Open()
command = New MySqlCommand(sql, con)
For i = 0 To parameters.Count - 1
command.Parameters.AddWithValue("#" & parameters(i).ToString, Values(i))
Next
command.CommandText = sql
command.ExecuteNonQuery()
con.Close()
End Sub
the method SaveUpdateDelete is applicable for adding, updating and deleting data.. your code will only differ in query... "insert, update, delete"