Here is the code:
Private Sub Button5_Click(sender As Object, e As EventArgs) Handles Button5.Click
con = New SqlConnection("Data Source=LAPTOP-16IIQENS\SQLEXPRESS;Initial Catalog=students;Integrated Security=True")
con.Open()
cmd = New SqlCommand("select * from data where [Roll No.]=#[Roll No.]", con)
cmd.Parameters.Add("#Roll No.", SqlDbType.Int).Value = TextBox5.Text
Dim adp As New SqlDataAdapter(cmd)
Dim table As New DataTable()
adp.Fill(table)
If (table.Rows.Count() > 0) Then
DataGridView1.DataSource = table
TextBox2.Text = table.Rows(0)(0).ToString
TextBox1.Text = table.Rows(0)(1).ToString
TextBox3.Text = table.Rows(0)(2).ToString
TextBox4.Text = table.Rows(0)(3).ToString
Else
MessageBox.Show("No Data Found")
End If
End Sub
enter image description here
You can freely choose the name of your SQL parameter, it does not need to match the name of the field.
Thus, if you call your parameter #RollNo instead of #Roll No. (no space, no dot), you no longer need to escape the name in your SQL, which should fix your current issue.
Change:
cmd = New SqlCommand("select * from data where [Roll No.]=#[Roll No.]", con)
cmd.Parameters.Add("#Roll No.", SqlDbType.Int).Value = TextBox5.Text
to:
cmd = New SqlCommand("select * from data where [Roll No.]=#RollNo", con)
cmd.Parameters.Add("#RollNo", SqlDbType.Int).Value = TextBox5.Text
Related
I want to make the time will fill automatically in Datetimepicker when I edit the price of my product. So, it can compare to the date of buying. So, I decided to use on_update_current_timestamp in MySQL database. My problem is how to convert a string into a date in Datagridview. Because when I was press the edit button it works but for the add button it's getting an error unable to convert MySQL date/time Is it have any solution to achieve my goal. If yes can u explain it. Thank u
Public Sub disp_data()
cmd = conn.CreateCommand()
cmd.CommandType = CommandType.Text
cmd.CommandText = "select * from produk"
cmd.ExecuteNonQuery()
Dim dt As New DataTable()
Dim da As New MySqlDataAdapter(cmd)
da.Fill(dt)
DataGridView1.DataSource = dt
End Sub
Private Sub tambah_btn_Click(sender As Object, e As EventArgs) Handles tambah_btn.Click
cmd = conn.CreateCommand()
cmd.CommandType = CommandType.Text
cmd.CommandText = $"insert into produk values('{kode.Text}','{nama.Text}','{harga.Text}','{DateTimePicker1.Value.ToString("dd/mm/yyyy")}')"
cmd.ExecuteNonQuery()
kode.Text = ""
nama.Text = ""
harga.Text = ""
disp_data()
MessageBox.Show("Data berhasil ditambahkan")
End Sub
You can do it (and it's better) like this:
'...
cmd = conn.CreateCommand()
cmd.CommandType = CommandType.Text
cmd.CommandText = "insert into produk values (#kode,#nama,#harga,#date)"
cmd.Parameters.AddWithValue("#kode", kode.Text)
cmd.Parameters.AddWithValue("#nama", nama.Text)
cmd.Parameters.AddWithValue("#harga", harga.Text)
cmd.Parameters.AddWithValue("#date", DateTimePicker1.Value.Date)
cmd.ExecuteNonQuery()
'...
let me know if it solves it, or if some adjustments are needed
how to insert and update data in database(sql server) with single button in vb.net i tried but not get the result.
here is my code.......
Private Sub Button5_Click(sender As System.Object, e As System.EventArgs) Handles Button5.Click
Try
Dim reader As SqlDataReader
Dim query As String
Dim n As Integer
n = 0
sqlcom1 = New SqlCommand("select * from mydatabase.masters")
sqlcom1.ExecuteReader()
sqlcom = New SqlCommand("select * from mydatabase.masters")
sqlcom.ExecuteReader()
reader = sqlcom1.ExecuteReader
reader = sqlcom.ExecuteReader
sqlcom = New SqlCommand("Update masters SET EmpName=#EmpName, Age=#Age, Address=#Address where Empid=#Empid", conn)
sqlcom.Parameters.Add("#EmpName", SqlDbType.VarChar).Value = TextBox4.Text
sqlcom.Parameters.Add("#Age", SqlDbType.Int).Value = TextBox3.Text
sqlcom.Parameters.Add("#Address", SqlDbType.VarChar).Value = TextBox2.Text
sqlcom.Parameters.Add("#Empid", SqlDbType.Int).Value = TextBox1.Text
sqlcom1 = New SqlCommand("insert into masters(Empid, EmpName, Age, Address) values(#Empid, #EmpName, #Age, #Address)", conn)
sqlcom1.Parameters.AddWithValue("#Empid", TextBox1.Text)
sqlcom1.Parameters.AddWithValue("#EmpName", TextBox4.Text)
sqlcom1.Parameters.AddWithValue("#Age", TextBox3.Text)
sqlcom1.Parameters.AddWithValue("#Address", TextBox2.Text)
conn.Open()
While reader.Read
n = n + 1
End While
If table.Rows.Count = n Then
sqlcom1.ExecuteNonQuery()
ElseIf table.Rows.Count = n + 1 Then
sqlcom.ExecuteNonQuery()
End If
Catch ex As Exception
MessageBox.Show("error" + ex.Message)
End Try
End Sub
Using block ensures that your connection object is closed and disposed even if there is an error.
Normally I put comments in line but the code got so cluttered that had to move most of them up here. I hope you can figure out where they belong.
Dim reader As SqlDataReader - Unused
Dim query As String - Unused
Integers are automatically initialized to zero
Pass the query and the connection to the constructor of the command.
Your connection string will tell SQL Server what database to use. It is not necessary in the query.
Apparently all you want is the count, not all the data.
This query is exactly the same as sqlcom1
Dim sqlcom As New SqlCommand("select * from mydatabase.masters", cn)
sqlcom.ExecuteReader()
You did this twice
reader = sqlcom1.ExecuteReader
Not necessay, we already retrieved the count
`While reader.Read
n = n + 1
End While`
I made the assumption that table was a DataTable populated at some other time. Using the count as comparison to the count in the table is not a great way to determine if the command is Insert or Update but it might work as long as database and table were not used with a DataAdapter that updated the database.
Private Sub Button5_Click(sender As System.Object, e As System.EventArgs) Handles Button5.Click
Try
Dim n As Integer
Using cn As New SqlConnection("Your connection string")
Dim sqlcom1 As New SqlCommand("select Count(*) from masters", cn)
cn.Open()
n = CInt(sqlcom1.ExecuteScalar) 'n is now the number of rows in the database table
Dim sqlcom As New SqlCommand
sqlcom.Parameters.Add("#EmpName", SqlDbType.VarChar).Value = TextBox4.Text
'Age is not a good idea to enter in a database. It changes over time.
'Enter the birth date and calculate the age as needed.
sqlcom.Parameters.Add("#Age", SqlDbType.Int).Value = CInt(TextBox3.Text)
sqlcom.Parameters.Add("#Address", SqlDbType.VarChar).Value = TextBox2.Text
If table.Rows.Count > n Then
'Normally EmpId would be an auto increment (identity) field
'and would NOT be included in an insert.
sqlcom.CommandText = "insert into masters(EmpName, Age, Address) values(#EmpName, #Age, #Address)"
Else
sqlcom.CommandText = "Update masters SET EmpName=#EmpName, Age=#Age, Address=#Address where Empid=#Empid"
sqlcom1.Parameters.Add("#Empid", SqlDbType.Int).Value = CInt(TextBox1.Text)
End If
sqlcom.ExecuteNonQuery()
End Using
Catch ex As Exception
MessageBox.Show("error" + ex.Message)
End Try
End Sub
On second thought, forget the whole thing. Use a DataGridView and a DataAdapter. Then you can just use Update and it will update, insert and delete.
I have a table that has columns CustomerCell and ReceiptType. I need to create a SELECT statement that displays every record that matches CustomerCell or ReceiptType.
I tried this code:
If TextBox1.Text.Trim.Length <> 0 OrElse CheckBox4.Checked = True Then
Dim Conn As New SqlConnection(constr)
Dim ds As New DataTable
Dim sqlstr As String = "Select [RcptNum], [RcptDate], [RcptCustName], [RcptCustCell], [RcptAmount], [RcptType], [RcptFld1], [RcptFld2], [RcptFld3], [RcptUser] From [tblReceipt] where (RcptCustCell = '" & TextBox1.Text & "') or ([RcptType] = 'Cash') "
Dim da As New SqlDataAdapter(sqlstr, Conn)
ds.Reset()
da = New SqlDataAdapter(sqlstr, Conn)
da.Fill(ds)
dgv.DataSource = ds
Call griddraw()
Conn.Close()
End If
Where Textbox1 is for CustomerCell and CheckBox4 is for ReceiptType. When I enter customer cell and receipt type I should see 2 records however with the above code I can see only one record.
This is my form:
As stated, look into parameters to avoid SQL injection and it does clear up your query a little more. I've put this together which may help. Might need a few tweaks for your application:
If TextBox1.Text.Trim.Length <> 0 OrElse CheckBox4.Checked = True Then
Dim dt As DataTable
Dim sqlstr As String = "Select [RcptNum], [RcptDate], [RcptCustName], [RcptCustCell], [RcptAmount], [RcptType], [RcptFld1], [RcptFld2], [RcptFld3], [RcptUser] From [tblReceipt] where (RcptCustCell = #RcptCustCell) or ([RcptType] = 'Cash') "
Using con As New SqlConnection(constr),
com As New SqlCommand(sqlstr, con)
com.Parameters.Add("#RcptCustCell", SqlDbType.VarChar).Value = TextBox1.Text
con.Open()
dt = New DataTable
dt.Load(com.ExecuteReader)
dgv.DataSource = dt
Call griddraw()
End Using
End If
Dim Conn As New SqlConnection(constr)
Dim ds As New DataTable
Dim sqlstr As String = "Select [RcptNum], [RcptDate], [RcptCustName], [RcptCustCell], [RcptAmount], [RcptType], [RcptFld1], [RcptFld2], [RcptFld3], [RcptUser] From [tblReceipt]"
If TextBox1.Text.trim.length <> 0 then
sqlstr += "where (RcptCustCell = '" & TextBox1.Text & "')"
endif
If chkPaymentCheck.checked then
if sqlstr.contains("where") = false then
sqlstr += "where RcptType = 'Check'"
EndIf
sqlstr += "or RcptType = 'Check'"
endif
Dim da As New SqlDataAdapter(sqlstr, Conn)
ds.Reset()
da = New SqlDataAdapter(sqlstr, Conn)
da.Fill(ds)
dgv.DataSource = ds
Call griddraw()
Conn.Close()
Try this and you can continue with the if statements to add more checks.
Public Sub FiltercmbSubCategory()
Dim sqlconn As New SqlClient.SqlConnection
sqlconn.ConnectionString = "server = SKPI-APPS1;" & _
"Database = EOEMS;integrated security=true"
Dim sqlcommand As SqlCommand
sqlconn.Open()
Dim da As New SqlDataAdapter("SELECT * FROM tblOfficeEquipmentSubCategory WHERE SUBCAT_ID = '" & cmbCategory.Text & "'", sqlconn)
Dim dt As New DataTable
da.Fill(dt)
cmbCategory.DataSource = dt
cmbCategory.DisplayMember = "SUBCAT_Name"
cmbCategory.ValueMember = "SUBCAT_ID"
sqlconn.Close()
End Sub
when i put this code on the form load event the data on the first combo box dissappears
also when i put this code on the index_changed of the first combobox
but when i commented this code it displays the records again in combobox 1
i need to filter the SUB_CATEGORY_COMBO_BOX based on the CATEGORY_COMBOBOX
Bind your first combobox inside:
if (!Page.IsPostBack)
{
// Bind combobox1 code here;
}
Now, on selectedindexchange call the code for binding subcategory combo.
Also, have look on your code again:
Dim da As New SqlDataAdapter("SELECT * FROM tblOfficeEquipmentSubCategory WHERE SUBCAT_ID = '" & cmbCategory.Text & "'", sqlconn)
Dim dt As New DataTable
da.Fill(dt)
cmbCategory.DataSource = dt
cmbCategory.DisplayMember = "SUBCAT_Name"
cmbCategory.ValueMember = "SUBCAT_ID"
In this code you are passing cmbCategory.Text as paramater for binding same dropdown cmbCategory. I think you have missed your second dropdown here. May be I am not correct but, it seems like that.
Is subcat_id a string or integer? If its integer drop the single quotes in your where clause.
Also to me it seems you are filling the same combobox that you select from with data, and not the sub box ?
cmbCategory[SUB?].DataSource = dt
You have used same object cmbCategory for both SUB_CATEGORY_COMBO_BOX based on the CATEGORY_COMBOBOX
You should use cmbSubCategory for SUB_CATEGORY_COMBO_BOX and cmbCategory for CATEGORY_COMBOBOX
Public Sub FiltercmbSubCategory()
Dim sqlconn As New SqlClient.SqlConnection
sqlconn.ConnectionString = "server = SKPI-APPS1;" & _
"Database = EOEMS;integrated security=true"
Dim sqlcommand As SqlCommand
sqlconn.Open()
Dim da As New SqlDataAdapter("SELECT * FROM tblOfficeEquipmentSubCategory WHERE SUBCAT_ID = '" & cmbCategory.Text & "'", sqlconn)
Dim dt As New DataTable
da.Fill(dt)
cmbSubCategory.DataSource = dt
cmbSubCategory.DisplayMember = "SUBCAT_Name"
cmbSubCategory.ValueMember = "SUBCAT_ID"
cmbSubCategory.databind();
sqlconn.Close()
End Sub
Hope this helps
Private Sub ComboBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ComboBox1.SelectedIndexChanged
ComboBox2.Items.Add(ComboBox1.SelectedIndex)
End Sub
I think is like this, what you want is, what you choose on 1combobox, it will display to combobox2 ?is like that?
UPDATE
Private Sub ComboBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles
sqlconn.Open()
Dim da1 As New SqlDataAdapter("SELECT Column_name FROM tblOfficeEquipmentSubCategory
WHERE column_name_ = '" % & combobox1.selecteditem & % "'", sqlconn)
From here >>> Dim dt1 As New DataTable
da1.Fill(dt)
cmbsubCategory.DataSource = dt1
cmbsubCategory.DisplayMember = "SUBCAT_Name"
cmbsubCategory.ValueMember = "SUBCAT_ID"
sqlconn.Close()
End Sub <<< till here, you need to change yourself
Dim sqlconn As New SqlClient.SqlConnection
sqlconn.ConnectionString = "server = SKPI-APPS1;" & _
"Database = EOEMS;integrated security=true"
Dim dt As New DataTable
sqlconn.Open()
Dim da As New SqlDataAdapter("SELECT SUBCAT_ID FROM tblOfficeEquipmentSubCategory WHERE CAT_ID = '" & cmbCategory.Text & "'", sqlconn)
da.Fill(dt)
cmbSubCategory.DataSource = dt
cmbSubCategory.DisplayMember = "SUBCAT_Name"
cmbSubCategory.ValueMember = "SUBCAT_ID"
sqlconn.Close()
got the correct answer thanks everyone
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdOk.Click
Dim scan As String = "select ProductCode from products where ProductCode = '" & TextBox1.Text & "';"
connection.Open()
Dim cmd = New MySqlCommand(scan, connection)
Dim dr As MySqlDataReader = cmd.ExecuteReader
If dr.Read = True Then
MsgBox("Match found")
connection.Close()
Dim insert As String = "insert into salesreport (ProductName,ProductPrice) select products.ProductName,products.ProductPrice from products where products.ProductCode = '" & TextBox1.Text & "';"
connection.Open()
da = New MySqlDataAdapter(insert, connection)
da.Fill(ds, "salesreport")
DataGridView1.DataSource = ds
DataGridView1.DataMember = "salesreport"
connection.Close()
Else
connection.Close()
MsgBox("No match found")
TextBox1.Text = ""
TextBox1.Select()
End If
End Sub
INSERT statements doesn't return records.
There is no sense in this situation to use a DataAdapter to INSERT a record.
Use the MySqlCommand.ExecuteNonQuery method to insert your record, then read the added row with a MySqlDataAdapter
Also, do not concatenate text, typed by your user, to build and use an sql text for the database engine. Your code could be easily used to create Sql Injection Attacks.
Dim scan As String = "select ProductCode from products " +
"where ProductCode = ?prodCode"
connection.Open()
Dim cmd = New MySqlCommand(scan, connection)
cmd.Parameters.AddWithValue("?prodCode", TextBox1.Text)
..........
Dim insert As String = "insert into salesreport (ProductName,ProductPrice) " +
"select products.ProductName,products.ProductPrice from products " +
"where products.ProductCode = ?prodCode"
cmd = new MySqlCommand(insert, connection)
cmd.Parameters.AddWithValue("?prodCode", TextBox1.Text)
cmd.ExecuteNonQuery()
da = New MySqlDataAdapter(scan, connection)
da.SelectCommand.Parameters.AddWithValue("?prodCode", TextBox1.Text)
da.Fill(ds, "salesreport")
DataGridView1.DataSource = ds
DataGridView1.DataMember = "salesreport"