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
Related
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
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
I created a search button to query my MS Access database and display the results but whenever I type in the ID and click search button it does nothing.
Everything else is working, it copies data from the VB form and stores it in the MS Access database but the search button does not query the database and retrieve the data.
Below is my code for the search button:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSearch.Click
Dim found As Boolean
Try
cm = New OleDb.OleDbCommand
With cm
.Connection = cn
.CommandType = CommandType.Text
.CommandText = "SELECT* FROM tblInfo WHERE (ID = #ID & txtFind.Text = #ID)"
dr = .ExecuteReader
End With
While dr.Read()
found = True
txtFirst1.Text = dr("Pfirst").ToString
txtMid1.Text = dr("Pmiddle").ToString
txtLast1.Text = dr("Plast").ToString
txtAdd1.Text = dr("Paddress").ToString
txtPhone1.Text = dr("Pphone").ToString
txtContact1.Text = dr("Pcontact").ToString
End While
cn.Close()
Exit Sub
If found = False Then MsgBox("Patient ID not found!", MsgBoxStyle.Critical)
dr.Close()
Catch ex As Exception
End Try
How can I solve this?
The issue is the attempt to pass the value of txtFind.Text into the command.
You want to use parameters:
With cm
.Connection = cn
.CommandType = CommandType.Text
.CommandText = "SELECT * FROM tblInfo WHERE ID = ?"
.Parameters.Add("#ID", OleDbType.[Type]).Value = txtFind.Text
dr = .ExecuteReader
End With
Note that I have used OleDbType.[Type]. You will want to replace this with the data type you have specified for column ID.
It also looks like you have missed opening the connection before calling ExecuteReader():
cn.Open()
I would consider implementing Using:
Sometimes your code requires an unmanaged resource, such as a file handle, a COM wrapper, or a SQL connection. A Using block guarantees the disposal of one or more such resources when your code is finished with them. This makes them available for other code to use.
Here is some sample code:
Using con As New OleDbConnection(connectionString),
cmd As New OleDbCommand("SELECT * FROM tblInfo WHERE ID = ?", con)
con.Open()
cmd.Parameters.Add("#ID", OleDbType.[Type]).Value = txtFind.Text
dr = cmd.ExecuteReader()
...
End Using
I tried to save all of records of 2 tables to Access database. My idea is save first table then save next table. But I think it isn't the right way when save multi tables to access because It take a long time.
Here is my code and it run ok but I don't know is there another ways which better to save multi tables to access.
Private Sub btnSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSave.Click
cnn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\1_Project\Project_of_VB_Net\AccessDatabase\StudentDatabase.accdb"
cmd.Connection = cnn
Dim cmdupdate As String
Dim cmdinsert As String
For Each dr In dt.Rows
cmdupdate = "UPDATE StudentData SET ID=#ID, StudentName=#StudentName, StudentID=#StudentID, StudentClass=#StudentClass WHERE StudentID=#StudentID"
cmdinsert = "INSERT INTO StudentData(ID,StudentName,StudentID,StudentClass) VALUES(#ID,#StudentName,#StudentID,#StudentClass)"
cmd.Parameters.Clear()
cmd.CommandText = cmdupdate
cmd.Parameters.AddWithValue("#ID", dr("ID"))
cmd.Parameters.AddWithValue("#StudentName", dr("StudentName"))
cmd.Parameters.AddWithValue("#StudentID", dr("StudentID"))
cmd.Parameters.AddWithValue("#StudentClass", dr("StudentClass"))
cnn.Open()
Dim count = cmd.ExecuteNonQuery()
If count = 0 Then
cmd.CommandText = cmdinsert
cmd.ExecuteNonQuery()
End If
cnn.Close()
Next
For Each dr2 In dt2.Rows
cmdupdate = "UPDATE StudentData2 SET ID2=#ID2, StudentName2=#StudentName2, StudentID2=#StudentID2, StudentClass2=#StudentClass2 WHERE StudentID2=#StudentID2"
cmdinsert = "INSERT INTO StudentData2(ID2,StudentName2,StudentID2,StudentClass2) VALUES(#ID2,#StudentName2,#StudentID2,#StudentClass2)"
cmd.Parameters.Clear()
cmd.CommandText = cmdupdate
cmd.Parameters.AddWithValue("#ID2", dr2("ID2"))
cmd.Parameters.AddWithValue("#StudentName2", dr2("StudentName2"))
cmd.Parameters.AddWithValue("#StudentID2", dr2("StudentID2"))
cmd.Parameters.AddWithValue("#StudentClass2", dr2("StudentClass2"))
cnn.Open()
Dim count2 = cmd.ExecuteNonQuery()
If count2 = 0 Then
cmd.CommandText = cmdinsert
cmd.ExecuteNonQuery()
End If
cnn.Close()
Next
End Sub
I want to display the result of my query in my Combobox but I'm getting an error "invalid argument or no parameter passed". Any advice is greatly appreciated. Here's my code.
Private Sub frmAdvancePayment_Load(sender As Object, e As EventArgs) Handles MyBase.Load
lstBillNum.Items.Clear()
txtLName.Text = frmAmortizationFee.txtLName.Text
txtFName.Text = frmAmortizationFee.txtFName.Text
lblMaAmount.Text = frmAmortizationFee.txtAmort.Text
lblAcctNum.Text = frmAmortizationFee.cmbAccountNo.Text
Dim connection_string As String = "Data Source=.\sqlexpress;Initial Catalog=CreditAndCollection;Integrated Security=True"
Dim Connection As New SqlConnection(connection_string)
Dim da As New SqlDataAdapter
Dim command As New SqlCommand
command.Connection = Connection
command.CommandText = "showBillingNum"
command.CommandType = CommandType.StoredProcedure
command.Parameters.AddWithValue("#AcctNum", lblAcctNum.Text)
Connection.Open()
da.SelectCommand = command
Dim dt As New DataSet
da.Fill(dt)
cmbBillNum.DataSource = dt
cmbBillNum.DisplayMember = "BillNum"
cmbBillNum.ValueMember = "BillNum"
command.ExecuteNonQuery()
Connection.Close()
End Sub
I would guess it is working but you are getting the error still? This is because the 3rd to last line:
command.ExecuteNonQuery()
executes the query after it has already been run. Not sure why that would produce that error but I know that line is wrong.