Search through the database using a combobox, if an item is in a database, prompt will appear - vb.net

Good day everyone.
I'm making a POS and Inventory Management System and I'm having a problem with this particular module as of now.
When adding an item to purchase order list, if an item is already in the purchaseorder database, the system will prompt that there is already a pending order. I've done the prompt, but the adding to the database was kinda messed up. It doesn't do a thing at all. The code there is working when I remove the ds.hasrows and while dr.read conditions. This is my code:
Private Sub btnSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSave.Click
Ceiling = CInt(txtCeiling.Text)
TotalQuantity = CurrentItemQuantity + CInt(txtPurchaseQty.Text)
If TotalQuantity > Ceiling Then
MsgBox("Exceeds Ceiling Point.")
Else
sqlString = "SELECT PRODUCT_ID FROM posinventory.purchaseorder WHERE purchaseorder.PRODUCT_ID = '" & cboProductID.Text & "'"
cmd = New MySqlCommand(sqlString, con)
dr = cmd.ExecuteReader
If dr.HasRows Then
While dr.Read
If CurrentItem = dr.Item("PRODUCT_ID") Then
MsgBox("Product has pending order.")
cboProductID.Focus()
Else
sqlString = "INSERT INTO posinventory.purchaseorder (PRODUCT_ID, PURCHASE_QUANTITY, DATE_PURCHASED, TIME_PURCHASED) VALUES (" & cboProductID.Text & ", '" & txtPurchaseQty.Text & "', '" & txtDate.Text & "', '" & txtTime.Text & "')"
Try
cmd = New MySqlCommand(sqlString, con)
dr = cmd.ExecuteReader
dr.Close()
Catch ex As Exception
MsgBox("Error saving to database. Error is: " & ex.Message)
Exit Sub
End Try
MsgBox("Transaction Complete.")
lvOrderList.Items.Clear()
sqlString = "SELECT posinventory.purchaseorder.TRANSACTION_ID, posinventory.products.PRODUCT_ID, posinventory.products.PRODUCT_NAME, posinventory.products.SUPPLIER_NAME, posinventory.purchaseorder.PURCHASE_QUANTITY, posinventory.purchaseorder.DATE_PURCHASED, posinventory.purchaseorder.TIME_PURCHASED FROM posinventory.purchaseorder, posinventory.products WHERE posinventory.purchaseorder.PRODUCT_ID = posinventory.products.PRODUCT_ID"
cmd = New MySqlCommand(sqlString, con)
da = New MySqlDataAdapter(cmd)
ds = New DataSet
da.Fill(ds, "Table")
Dim i As Integer = 0
Dim j As Integer = 0
For i = 0 To ds.Tables(0).Rows.Count - 1
For j = 0 To ds.Tables(0).Columns.Count - 1
itemcol(j) = ds.Tables(0).Rows(i)(j).ToString()
Next
Dim lvi As New ListViewItem(itemcol)
Me.lvOrderList.Items.Add(lvi)
Next
grpCreateOrder.Enabled = False
grpOrderList.Enabled = True
cboProductID.SelectedIndex = -1
txtPurchaseQty.Text = ""
txtDate.Text = ""
txtTime.Text = ""
txtProductName.Text = ""
txtSupplier.Text = ""
txtQty.Text = ""
txtCeiling.Text = ""
btnBack.Enabled = True
End If
End While
End If
dr.Close()
End If
End Sub

I think its because you are inside of a loop using a cmd and dr. While you are in there you are then defining a new cmd and dr.
Try using different names eg cmd2, dr2.

Related

VB.net and SQL .... For multiple read of database table

Im am currently coding an handsfree RFID attendance monitoring system where i could just swipe and record details automatically...
I've been in trouble about this piece of code where i need to fetch a table and another table inorder to check if there is an existing record in table1 as the details and table2 as a record in in/out. I wanted it as much as possible to be able to be in a 1 while loop
**
I kept getting this error **
Invalid attempt to access a field before calling Read()
`
Private Sub TextBox7_KeyDown(sender As Object, e As KeyEventArgs) Handles TextBox7.KeyDown
If e.KeyCode = Keys.Enter Then
'Dim idnum = Val(TextBox7.Text
Dim statu As String = ""
Dim idnum = (TextBox7.Text)
Dim record As String = ""
TextBox2.Text = ""
TextBox3.Text = ""
TextBox4.Text = ""
ConnectToDB()
sql = "select * from rfidmaintest.student_details_dub where f9 = '" & idnum & "'"
cmd = New MySqlCommand(sql, cn)
dr = cmd.ExecuteReader
While dr.Read
TextBox2.Text = (dr("f2"))
TextBox3.Text = (dr("f9"))
TextBox4.Text = (dr("f4"))
TextBox5.Text = (dr("f14"))
TextBox6.Text = (dr("f3"))
TextBox7.Clear()
dr.Close()
cn.Close()
'ANOTHER FETCH
ConnectToDB()
sql = "select * from rfidmaintest.monitoring where id_num = '" & idnum & "'"
cmd = New MySqlCommand(sql, cn)
dr = cmd.ExecuteReader
**Invalid attempt to access a field before calling Read()**
If (dr("entry_record")) = String.Empty Then
status.Text = "IN"
End If
If status.Text = "IN" Then
status.Text = (dr("entry_record"))
record = "OUT"
ElseIf status.Text = "OUT" Then
record = "IN"
ElseIf status.Text = String.Empty Then
record = "IN"
End If
End While
dr.Close()
cn.Close()
`
I tried to call the table
You need another dr.read for the second query or you can use another reader, for example like dr2.read.
Your first While dr.read already closed with dr.close, you need to reopen the reader to continue to read the second query

VB.net and DATABASE. i Kept getting an record without an Entry Level record (IN)

i kept getting an record without an Entry Level record (IN) that supposably will have an IN(database record) instead of NOTHING... However after it was scanned after another try only when IN is found in the database.... Overall I will just make an details but empty entry_record which is incomplete
enter image description here
Private Sub TextBox7_KeyDown(sender As Object, e As KeyEventArgs) Handles TextBox7.KeyDown
If e.KeyCode = Keys.Enter Then
'Dim idnum = Val(TextBox7.Text
Dim statu As String = ""
Dim idnum = (TextBox7.Text)
Dim record As String = ""
TextBox2.Text = ""
TextBox3.Text = ""
TextBox4.Text = ""
ConnectToDB()
sql = "select * from rfidmaintest.student_details_dub where f9 = '" & idnum & "'"
cmd = New MySqlCommand(sql, cn)
dr = cmd.ExecuteReader
While dr.Read
TextBox2.Text = (dr("f2"))
TextBox3.Text = (dr("f9"))
TextBox4.Text = (dr("f4"))
TextBox5.Text = (dr("f14"))
TextBox6.Text = (dr("f3"))
TextBox7.Clear()
End While
dr.Close()
cn.Close()
'ANOTHER FETCH
ConnectToDB()
sql = "select * from rfidmaintest.monitoring where id_num = '" & idnum & "'"
cmd = New MySqlCommand(sql, cn)
dr = cmd.ExecuteReader
While dr.Read
If (dr("entry_record")) = "IN" Then
record = "OUT"
ElseIf (dr("entry_record")) = "OUT" Then
record = "IN"
ElseIf (dr("entry_record")) = String.Empty Then
record = "IN"
End If
status.Text = (record)
End While
dr.Close()
cn.Close()
ConnectToDB()
sql = "insert into monitoring (id_num, fname, lname, status, entry_record, floor_level, date) VALUES (#num, #name, #lname, #stat, #record, #lev,#date)"
cmd = New MySqlCommand(sql, cn)
With cmd
.Parameters.AddWithValue("#num", idnum)
.Parameters.AddWithValue("#name", TextBox2.Text)
.Parameters.AddWithValue("#lname", TextBox6.Text)
.Parameters.AddWithValue("#stat", TextBox5.Text)
.Parameters.AddWithValue("#lev", levellock.sharevalue)
.Parameters.AddWithValue("#record", status.Text)
.Parameters.AddWithValue("#date", Date.Now)
.ExecuteReader()
End With
MsgBox("Details has been saved!", vbInformation, "Saved")
cmd = Nothing
dr.Close()
cn.Close()
End If
End Sub
ConnectToDB()
sql = "select * from rfidmaintest.student_details_dub where f9 = '" & idnum & "'"
cmd = New MySqlCommand(sql, cn)
dr = cmd.ExecuteReader
While dr.Read
TextBox2.Text = (dr("f2"))
TextBox3.Text = (dr("f9"))
TextBox4.Text = (dr("f4"))
TextBox5.Text = (dr("f14"))
TextBox6.Text = (dr("f3"))
TextBox7.Clear()
status.Text = "IN"
End While
dr.Close()
cn.Close()
'ANOTHER FETCH
ConnectToDB()
sql = "select * from rfidmaintest.monitoring where id_num = '" & idnum & "'"
cmd = New MySqlCommand(sql, cn)
dr = cmd.ExecuteReader
While dr.Read
'If status.Text = "IN" Then
'record = "OUT"
' ElseIf status.Text = "OUT" Then
' record = "IN"
' ElseIf status.Text = String.Empty Then
' record = "IN"
' End If
'status.Text = (record)
If (dr("entry_record")) = "IN" Then
record = "OUT"
ElseIf (dr("entry_record")) = "OUT" Then
record = "IN"
ElseIf (dr("entry_record")) = String.Empty Then
record = "IN"
End If
status.Text = (record)
End While
dr.Close()
cn.Close()
stated the STATUS as IN

Use VB.NET Manipulate Microsoft Access Database

How can I make this work?
Private Sub ListView_MouseClick(sender As Object, e As MouseEventArgs) Handles ListView.MouseClick
conndb = New OleDbConnection
conndb.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\Database1.accdb"
Try
conndb.Open()
Dim str As String
str = "Select * FROM customer WHERE CustomerID = '" & ListView.FocusedItem.Text & "'"
COMMAND = New OleDbCommand(str, conndb)
dr = COMMAND.ExecuteReader
If dr.Read = True Then
txtID.Text = dr("CustomerID")
txtFirstName.Text = dr("FirstName")
txtSurname.Text = dr("Surname")
txtAddress.Text = dr("Address")
txtCN1.Text = dr("ContactNo1")
txtCN2.Text = dr("ContactNo2")
txtEmail.Text = dr("EmailAddress")
txtRemarks.Text = dr("Remarks")
txtDebtStatus.Text = dr("DebtStatus")
txtDownPay.Text = dr("DownPayment")
txtDebtBal.Text = dr("DebtBal")
txtCustomerDate.Text = dr("Date")
End If
Catch ex As Exception
MessageBox.Show(ex.Message)
Finally
conndb.Dispose()
End Try
End Sub
I need help on how can I make this run without errors, Im using ms access as my database source. There seems to be an error using this code, this code works perfectly fine with mysql but in ms access, it says data mistype error or something like that. Need your help, thanks
Remove the ' surrounding the field CustomerID in your query :
str = "Select * FROM customer WHERE CustomerID = '" & ListView.FocusedItem.Text & "'"
becomes :
str = "Select * FROM customer WHERE CustomerID = " & ListView.FocusedItem.Text
MS Access sees a string when you put an apostrophe, so there is a Type Mismatch Exception, because it is expecting a number...
However, this is a pretty bad idea as Parametrized queries are a better way of doing this (see : Why should I create Parametrized Queries ?)
Also, Use Using
So all in all, it's just another brick in the wall :
Private Sub ListView_MouseClick(sender As Object, e As MouseEventArgs) Handles ListView.MouseClick
Using conndb As New OleDbConnection
conndb.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\Database1.accdb"
Try
conndb.Open()
Dim str As String
str = "Select * FROM customer WHERE CustomerID = #Customer"
Using COMMAND As New OleDbCommand(str, conndb)
COMMAND.Parameters.Add("#Customer", SqlDbType.Integer).Value = Integer.Parse(ListView.FocusedItem.Text)
dr = COMMAND.ExecuteReader
If dr.Read = True Then
txtID.Text = dr("CustomerID")
txtFirstName.Text = dr("FirstName")
txtSurname.Text = dr("Surname")
txtAddress.Text = dr("Address")
txtCN1.Text = dr("ContactNo1")
txtCN2.Text = dr("ContactNo2")
txtEmail.Text = dr("EmailAddress")
txtRemarks.Text = dr("Remarks")
txtDebtStatus.Text = dr("DebtStatus")
txtDownPay.Text = dr("DownPayment")
txtDebtBal.Text = dr("DebtBal")
txtCustomerDate.Text = dr("Date")
End If
End Using
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Using
End Sub
Take a look at this sample code that I put together a while back. You can probably learn a lot from this.
Private Sub TextBox1_TextChanged(sender As System.Object, e As System.EventArgs) Handles TextBox1.TextChanged, TextBox1.Click
Dim connectionString As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\your_path\Desktop\Northwind_2012.mdb"
Dim selectCommand As String
Dim connection As New OleDbConnection(connectionString)
'selectCommand = "Select * From MyExcelTable where Fname = '" & TextBox1.Text & "'"
'"SELECT * FROM Customers WHERE Address LIKE '" & strAddressSearch & "%'"
'or ending with:
'"SELECT * FROM Customers WHERE Address LIKE '%" & strAddressSearch & "'"
selectCommand = "Select * From MyExcelTable where Fname Like '" & TextBox1.Text & "%'"
Me.dataAdapter = New OleDbDataAdapter(selectCommand, connection)
With DataGridView1
.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCells
.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.ColumnHeader
.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.ColumnHeader
End With
Dim commandBuilder As New OleDbCommandBuilder(Me.dataAdapter)
Dim table As New DataTable()
table.Locale = System.Globalization.CultureInfo.InvariantCulture
Me.dataAdapter.Fill(table)
Me.bindingSource1.DataSource = table
Dim data As New DataSet()
data.Locale = System.Globalization.CultureInfo.InvariantCulture
DataGridView1.DataSource = Me.bindingSource1
Me.DataGridView1.AlternatingRowsDefaultCellStyle.BackColor = Color.Aqua
Me.DataGridView1.AutoResizeColumns( _
DataGridViewAutoSizeColumnsMode.AllCells)
End Sub

How to have restriction in comparing textbox value?

Private Sub txtuser_LostFocus(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtuser.LostFocus
Try
con.Open()
adapter.Fill(table)
sql = "Select * from login "
command = New MySqlCommand(sql, con)
myreader = command.ExecuteReader
Dim a As Integer
Dim b As Integer
a = table.Rows.Count
a -= 1
b = 0
If table.Rows.Count > 0 Then
While (b <= a)
If txtuser.Text = table.Rows(b).Item("username") Then
usercons.Visible = True
PictureBox1.Visible = False
txtuser.Text = ""
btnsave.Enabled = False
ElseIf Not txtuser.Text = table.Rows(b).Item("username") Then
usercons.Visible = False
PictureBox1.Visible = True
btnsave.Enabled = False
End If
b += 1
End While
End If
Catch ex As MySqlException
MsgBox("An Error Occurred. " & ex.Number & " – " & ex.Message)
End Try
con.Close()
End Sub
This is the quick but highly dangerous way of doing it open to all sorts of abuse:
sql = "Select * from login WHERE username='" & txtuser.Text & "'
There is a better way, create a parameter:
con.Open()
adapter.Fill(table)
sql = "Select * from login WHERE username=#username"
command = New MySqlCommand(sql, con)
Dim param As New SqlParameter("#username", SqlDbType.VarChar)
command.Parameters.Add(param)
myreader = command.ExecuteReader
Then check the Rows property, if more than 0 rows, you have selected the user.

I am getting Error "There is no row at position 0" from code below

Private Sub Button3_Click (ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
If txtID.Text = "" Then
MsgBox("Please input a valid Employee code to load a corresponding record", MsgBoxStyle.Information)
Else
dbProvider = "Provider=Microsoft.Ace.OLEDB.12.0;"
dbSource = "Data Source = C:\Users\Blessing\Documents\IBCARIP.accdb;Persist Security Info=False"
con.ConnectionString = dbProvider & dbSource
con.Open()
sql = "select * from Calculator where " _
& "EmpCode = " & " '" & txtID.Text & "'"
da = New OleDb.OleDbDataAdapter(sql, con)
da.Fill(ds, "IBCARIP")
lblSAI.Text = ds.Tables("IBCARIP").Rows(inc).Item("SName") & ds.Tables("IBCARIP").Rows(inc).Item("FName")
lblRate.Text = ds.Tables("IBCARIP").Rows(inc).Item("NRate")
lblOT.Text = ds.Tables("IBCARIP").Rows(inc).Item("OTRate")
lblBnk.Text = ds.Tables("IBCARIP").Rows(inc).Item("BName") & ".." & ds.Tables("IBCARIP").Rows(inc).Item("ANumber") & ".." & ds.Tables("IBCARIP").Rows(inc).Item("AType")
con.Close()
ds.Tables("IBCARIP").DataSet.Clear()
MaxRows = ds.Tables("IBCARIP").Rows.Count
'inc = 0
End If
End Sub
The message comes when i enter a wrong or non-existent Employee code in txtID.text
how can i solve tha problem
try as below
you should always check dataset table and rows count
i am not much familiar with vb .net(i am in C#) but i think following is good to go
If txtID.Text = "" Then
MsgBox("Please input a valid Employee code to load a corresponding record", MsgBoxStyle.Information)
Else
dbProvider = "Provider=Microsoft.Ace.OLEDB.12.0;"
dbSource = "Data Source = C:\Users\Blessing\Documents\IBCARIP.accdb;Persist Security Info=False"
con.ConnectionString = dbProvider & dbSource
con.Open()
sql = "select * from Calculator where " _
& "EmpCode = " & " '" & txtID.Text & "'"
da = New OleDb.OleDbDataAdapter(sql, con)
da.Fill(ds, "IBCARIP")
If ds.Tables.Count > 0 AndAlso ds.Tables("IBCARIP").Rows.Count >0 Then
lblSAI.Text = ds.Tables("IBCARIP").Rows(inc).Item("SName") & ds.Tables("IBCARIP").Rows(inc).Item("FName")
lblRate.Text = ds.Tables("IBCARIP").Rows(inc).Item("NRate")
lblOT.Text = ds.Tables("IBCARIP").Rows(inc).Item("OTRate")
lblBnk.Text = ds.Tables("IBCARIP").Rows(inc).Item("BName") & ".." & ds.Tables("IBCARIP").Rows(inc).Item("ANumber") & ".." & ds.Tables("IBCARIP").Rows(inc).Item("AType")
con.Close()
ds.Tables("IBCARIP").DataSet.Clear()
MaxRows = ds.Tables("IBCARIP").Rows.Count
'inc = 0
End if
End If
End Sub
First the most important: you are open for SQL-Injection since you are not using sql-parameters but concatenating the query with user input.
The reason for the error is that you are trying to access the a DataRow in the DataTable without checking if there is at least one. But you are accessing the row with index inc, maybe the table does not contain so many rows. Why do you use a variable at all here?
da.Fill(ds, "IBCARIP")
If ds.Tables("IBCARIP").Rows.Count = 0 Then Return ' or something else
' here you can safely access the first row...
Here the long version with parameters:
Using con = New OleDbConnection(dbProvider & dbSource)
Dim sql = "select * from Calculator where EmpCode=?"
Using da = New OleDbDataAdapter(sql, con)
da.SelectCommand.Parameters.AddWithValue("#EmpCode", txtID.Text)
da.Fill(ds, "IBCARIP")
If ds.Tables("").Rows.Count > 0 Then
Dim row = ds.Tables("IBCARIP").Rows(0)
Dim SName = row.Field(Of String)("SName")
Dim FName = row.Field(Of String)("FName")
Dim sai = String.Format("{0}{1}", SName, FName)
lblSAI.Text = sai
' ... '
End If
End Using
End Using