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.
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
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
Dim cmd As OleDbCommand = New OleDbCommand(Sql, con)
Dim strSql As String = "Select EmpName,Count(EmpName) from tblPO where OrderType='" &
"B2B" & "' and POExpireDate < #LogDate Group By EmpName"
Dim tstDate As DateTime = DateTime.Now
Dim dateAsString As String = tstDate.ToString("dd/MM/yy")
cmd.Parameters.AddWithValue("#LogDate", CType(dateAsString, String))
Dim dtb As New DataTable
Using dad As New OleDbDataAdapter(strSql, con)
dad.Fill(dtb)
End Using
con.Close()
I'm working in VB.NET
NO value given for one or more given parameters
error coming while filling datatable..why...how could I fix this.
pls help
Your problem is that you are passing your strSql and the connection to the data adapter but not the command which is what contains the parameter. Pass the command instead
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
'Using blocks ensure that your database objects are
'Closed And Disposed even if there Is an error.
Dim dtb As New DataTable
Using con As New OleDbConnection("Your connection string")
Dim strSql As String = "Select EmpName,Count(EmpName) from tblPO where OrderType = 'B2B' and POExpireDate < #LogDate Group By EmpName;"
Using cmd As OleDbCommand = New OleDbCommand(strSql, con)
cmd.Parameters.Add("#LogDate", OleDbType.Date).Value = DateTime.Now
'On the next line pass the command, no need to pass connection
'because it has already been passed to the constructor of the command
Using dad As New OleDbDataAdapter(cmd)
dad.Fill(dtb)
End Using
End Using
End Using
End Sub
I have a Database named DataOberge and a Table named TableOberge with fields (Id, FirstName, Phone, DateOut, HourOut, DateIN, HourIN). Fields DateOut and DateIN are of type Date. Fields HourOut and HourIN are of type Time.
How to display in datagridview2 the people who arrive today's Date and Time its depends on the field DateIN and HourIN?
This is all my code :
Imports System.Data.SqlClient
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim InfoCommand As SqlCommand
Dim StrCon As SqlConnection = Nothing
Try
StrCon = New SqlConnection("data source=ABIDINE; initial catalog= DataOberge;User ID=sa;Password=123456789;")
Using DepCom As SqlCommand = New SqlCommand("Select * From TableOberge", StrCon)
StrCon.Open()
Using DepAdap As SqlDataAdapter = New SqlDataAdapter(DepCom)
Dim DepDT As DataTable = New DataTable
DepAdap.Fill(DepDT)
DataGridView1.DataSource = DepDT
Dim CurrentBs As BindingSource = New BindingSource()
CurrentBs.DataSource = DepDT
DataGridView2.DataSource = CurrentBs
'CurrentBs.Filter = String.Format("[DateIN] = #{0}# AND [HourIN] >= #{1}#", DateTime.Now.Date, DateTime.Now.Hour)
CurrentBs.Filter = String.Format("[DateIN] = #{0}# AND [HourIN] >= #{1}#", DateTime.Now.Date, DateTime.Now.Hour)
End Using
StrCon.Close()
End Using
Catch ex As Exception
Console.WriteLine(ex.Message)
Finally
If StrCon IsNot Nothing Then
If StrCon.State = ConnectionState.Open Then
StrCon.Close()
End If
StrCon.Dispose()
End If
End Try
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim StrCon As New SqlConnection
StrCon = New SqlConnection("data source=ABIDINE; initial catalog= DataOberge;User ID=sa;Password=123456789;")
Using Command As New SqlCommand With {.Connection = StrCon}
With Command
.CommandText = "INSERT INTO [TableOberge] ([ID], [FIRSTNAME], [PHONE], [ADRESSE], [DATE_OUT], [HOUR_OUT], [DATE_IN], [HOUR_IN]) VALUES (#ID, #FIRSTNAME, #PHONE, #ADRESSE, #DATE_OUT, #HOUR_OUT, #DATE_IN, #HOUR_IN)"
.Parameters.Add("#ID", SqlDbType.Int).Value = TextBox1.Text
.Parameters.Add("#FIRSTNAME", SqlDbType.NVarChar).Value = TextBox2.Text
.Parameters.Add("#PHONE", SqlDbType.NVarChar).Value = TextBox3.Text
.Parameters.Add("#ADRESSE", SqlDbType.NVarChar).Value = TextBox4.Text
.Parameters.Add("#DATE_OUT", SqlDbType.Date).Value = TextBox5.Text
.Parameters.Add("#HOUR_OUT", SqlDbType.Time).Value = TextBox6.Text
.Parameters.Add("#DATE_IN", SqlDbType.Date).Value = TextBox7.Text
.Parameters.Add("#HOUR_IN", SqlDbType.Time).Value = TextBox8.Text
End With
If StrCon.State = ConnectionState.Closed Then StrCon.Open()
If Command.ExecuteNonQuery() = 1 Then
MsgBox("SUCCED ADD", MsgBoxStyle.MsgBoxRtlReading, "SUCCES")
Else
MsgBox("ERROR FATAL", MsgBoxStyle.MsgBoxRtlReading, "ERROR")
End If
StrCon.Close()
End Using
End Sub
You would specify a WHERE clause in your SQL command that populates the data in DataGridView2. It would probably be best to add a BindingSource to your Form and bind it to the DataTable you populated, this is so you can set the filter. Try something like this:
'Declare the connection object
Dim StrCon As SqlConnection = Nothing
'Wrap code in Try/Catch
Try
'Set the connection object to a new instance
'TODO: Change "My Connection String Here" with a valid connection string
StrCon = New SqlConnection("My Connection String Here")
'Create a new instance of the command object
Using DepCom As SqlCommand = New SqlCommand("Select * From TableOberge", StrCon)
'Open the connection
StrCon.Open()
'Create a new instance of the data adapter object
Using DepAdap As SqlDataAdapter = New SqlDataAdapter(DepCom)
'Create a new instance of a DataTable
Dim DepDT As DataTable = New DataTable
'Use the DataAdapter to fill the data from the SqlCommand into the DataTable
DepAdap.Fill(DepDT)
'Set the DataSource of the DataGridView to the filled DataTable
DataGridView1.DataSource = DepDT
'Create a new instance of a BindingSource
Dim CurrentBs As BindingSource = New BindingSource()
'Setup the properties of the BindingSource
CurrentBs.DataSource = DepDT
'Bind the BindingSource to the DataGridView
DataGridView2.DataSource = CurrentBs
'Filter the data in the BindingSource to today's date and anything on or after the current hour
CurrentBs.Filter = $"[DateIN] = #{DateTime.Now.Date}# AND [HourIN] >= #{DateTime.Now.Hour}#"
End Using
'Close the connection
StrCon.Close()
End Using
Catch ex As Exception
'Display the error
Console.WriteLine(ex.Message)
Finally
'Check if the connection object was initialized
If StrCon IsNot Nothing Then
If StrCon.State = ConnectionState.Open Then
'Close the connection if it was left open(exception thrown)
StrCon.Close()
End If
'Dispose of the connection object
StrCon.Dispose()
End If
End Try
Alternatively, if you didn't want to use the BindingSource, then just create a new SqlCommand and SqlDataAdapter and then do the same thing only for your DataGridView2 using the appropriate SQL query.
UPDATE
In my example I use String Interpolation, but I found that the OP is using a version of Visual Studios that does not support it. Because of this, change the following:
'From:
CurrentBs.Filter = $"[DateIN] = #{DateTime.Now.Date}# AND [HourIN] >= #{DateTime.Now.Hour}#"
'To:
CurrentBs.Filter = String.Format("[DateIN] = #{0}# AND [HourIN] >= #{1}#", DateTime.Now.Date, DateTime.Now.Hour)
I am doing a college assignment and have been trying to figure it out for hours, but I cant seem to get my new customer to save to the database! Please, I would really, REALLY apreciate it if you could have a look at my code, make any suggestions, or let me know more efficient ways of doing this. Bellow I provide a sample of my code for this.
To begin with, on form load I determine the new customer ID to be put into the database:
Private Sub frmRegister_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'Me.CustomerTableAdapter.Fill(Me.DatabasePizzaPalaceDataSet.Customer)
Dim conn As New System.Data.OleDb.OleDbConnection()
conn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=H:\Year 2\Unit 17 Project Planning\Workto do\PizzaPalce\Program\DatabasePizzaPalace.accdb"
conn.Open()
Dim Rows As Integer
Dim sql As String = "SELECT * FROM Customer"
Dim da As OleDb.OleDbDataAdapter
Dim ds As New DataSet
da = New OleDb.OleDbDataAdapter(sql, conn)
da.Fill(ds, "Customer")
Rows = ds.Tables("Customer").Rows.Count
NewCustomerID.Text = Rows + 1
Customer_IDTextBox.Text = NewCustomerID.Text
conn.Close()
End Sub
Now that being said, here is the piece of code I run when clicking on my save button for the recrod to be added through a new data row.
Private Sub btnSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSave.Click
Dim conn As New System.Data.OleDb.OleDbConnection()
conn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=H:\Year 2\Unit 17 Project Planning\Workto do\PizzaPalce\Program\DatabasePizzaPalace.accdb"
conn.Open()
Dim inc As Integer
Dim sql As String = "SELECT * FROM Customer"
Dim da As OleDb.OleDbDataAdapter
Dim ds As New DataSet
da = New OleDb.OleDbDataAdapter(sql, conn)
da.Fill(ds, "Customer")
inc = Customer_IDTextBox.Text
If inc <> -1 Then
Dim cb As New OleDb.OleDbCommandBuilder(da)
Dim dsNewRow As DataRow
dsNewRow = ds.Tables("Customer").NewRow()
dsNewRow.Item("Customer_ID") = Customer_IDTextBox.Text
dsNewRow.Item("Username_Email") = Username_EmailTextBox.Text
dsNewRow.Item("Password") = PasswordTextBox.Text
dsNewRow.Item("First_Name") = First_NameTextBox.Text
dsNewRow.Item("Surname") = SurnameTextBox.Text
dsNewRow.Item("Mobile") = MobileTextBox.Text
dsNewRow.Item("House") = HouseTextBox.Text
ds.Tables("Customer").Rows.Add(dsNewRow)
da.Update(ds, "Customer")
MsgBox("New Record added to the Database")
conn.Close()
frmLogin.Show()
End If
'Dim cb As New OleDb.OleDbCommandBuilder(da)
'Me.CustomerTableAdapter.Insert(Customer_IDTextBox.Text, Username_EmailTextBox.Text, PasswordTextBox.Text, First_NameTextBox.Text, SurnameTextBox.Text, MobileTextBox.Text, HouseTextBox.Text)
'Me.CustomerTableAdapter.Fill(Me.DatabasePizzaPalaceDataSet.Customer)
'Me.Validate()
'Me.CustomerBindingSource.EndEdit()
'Me.CustomerTableAdapter.Fill(DatabasePizzaPalaceDataSet.Customer)
'Me.TableAdapterManager.UpdateAll(Me.DatabasePizzaPalaceDataSet)
'da.Update(ds, "Customer")
'MsgBox("You have been succesfully registerd with us. Thanks!")
'conn.Close()
'frmLogin.Show()
End Sub
In comments you can also see a code provided by my teacher, which we are supposed to improve, I just wish to find a way of making this work!
Thanks a lot, all help and suggestions are very appreciated.
Instead of ds.Tables("Customer") I used ds.Tables(0) (or whatever index your table is at inside your DataSet.)
Dim con As New OleDbConnection(_myConn) ''_myConn should be your connection string
con.Open()
Dim da As OleDbDataAdapter
Dim ds As New DataSet
da = New OleDbDataAdapter("select * from customer", con)
da.Fill(ds)
Dim cb As New OleDbCommandBuilder(da)
Dim dsNewRow As DataRow
dsNewRow = ds.Tables(0).NewRow()
dsNewRow.Item(1) = "1"
dsNewRow.Item(2) = "Blah"
dsNewRow.Item(3) = "Test"
dsNewRow.Item(4) = "T"
dsNewRow.Item(5) = "T"
dsNewRow.Item(6) = "T"
dsNewRow.Item(7) = "20000101"
ds.Tables(0).Rows.Add(dsNewRow)
da.Update(ds.Tables(0))
con.Close()
It's important to realize your database schema also. If your first column is an identity auto increment column, you want to avoid trying to insert anything to that column. I prefer to use the Indexes because it's a lot easier to misspell a column name as a string, although it may not be as clear.
So, Customer_ID may be (or not be) an auto-increment field, which means trying to insert data into that column will result in an error.