I am getting Error "There is no row at position 0" from code below - vb.net

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

Related

Multiselection in vb.net ListBox

I have a list of student names in a listBox,(studentList)I click on a name in the box and get all the students details up ie name, course, subject etc.The code then gets the details from the database(in my case it's access) then displays it in a datagridview.
The code works fine if I just select one item from one(or all)List Boxes.My question is, can I select more than one item per LitsBox.I know I can use SelectedMode property to allow the highlighting but that wont draw the required data from the database.Here is the code I am using vb.10
`Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim con As New OleDb.OleDbConnection
Dim dbProvider As String
Dim dbSource As String
Dim ds As New DataSet
Dim tables As DataTableCollection = ds.Tables
Dim source1 As New BindingSource()
Dim da As New OleDb.OleDbDataAdapter
dbProvider = "PROVIDER=Microsoft.ACE.OLEDB.12.0;"
dbSource = "Data Source = C:\Documents and Settings\Desktop \studentmarks.accdb"
con.ConnectionString = dbProvider & dbSource
con.Open()
Dim isFirstColumn As Boolean = True
Dim student As String = ""
Dim course As String = ""
Dim grade As String = ""
Dim x As String = studentList.Text
Dim y As String = courseList.Text
Dim z As String = gradeList.Text
Dim defaultSQL As String = "SELECT * FROM studentfile "
If studentList.SelectedIndex > -1 Then
If isFirstColumn Then
student = "WHERE student = '" & x & "' "
Else
student = "AND student = '" & x & "' "
End If
isFirstColumn = False
End If
If courseList.SelectedIndex > -1 Then
If isFirstColumn Then
course = "WHERE course = '" & y & "' "
Else
course = "AND course = '" & y & "' "
End If
isFirstColumn = False
End If
If gradeList.SelectedIndex > -1 Then
If isFirstColumn Then
grade = "WHERE grade = '" & z & "' "
Else
grade = "AND grade = '" & z & "' "
End If
isFirstColumn = False
End If
Dim sql As String = defaultSQL & student & course & grade
da = New OleDb.OleDbDataAdapter(sql, con)
da.Fill(ds, "topclass")
Dim view1 As New DataView(tables(0))
source1.DataSource = view1
DataGridView1.DataSource = view1
DataGridView1.Refresh()
DataGridView1.DataSource = view1
DataGridView1.Refresh()
Dim cnt As Integer
cnt = DataGridView1.Rows.Count
TextBox1.Text = cnt - 1
Dim dayclass As String = TextBox1.Text
TextBox8.Text = dayclass
con.Close()
End Sub`
many thanks
grey
Using the .SelectedItems (and a lot of jiggery with the where clause.... you should be able to use this to EITHER have multi-select of single select accross all three listboxes as well as not selecting anything from any of them too...
The only question I would have would be whether you want all the 'AND's as this would mean if you selected two students, you wouldnt get any results... as no two students are the same right? Unless you selected two 'Dave's in which it would return both. For example!
Might suggest changing some for 'OR's or look at what the end result might be? Either way comment and let us know if need any further help
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim con As New OleDb.OleDbConnection
Dim dbProvider As String
Dim dbSource As String
Dim ds As New DataSet
Dim tables As DataTableCollection = ds.Tables
Dim source1 As New BindingSource()
Dim da As New OleDb.OleDbDataAdapter
dbProvider = "PROVIDER=Microsoft.ACE.OLEDB.12.0;"
dbSource = "Data Source = C:\Documents and Settings\Desktop \studentmarks.accdb"
con.ConnectionString = dbProvider & dbSource
con.Open()
Dim student As String = ""
Dim course As String = ""
Dim grade As String = ""
Dim defaultSQL As String = "SELECT * FROM studentfile "
Dim WhereClause As String = ""
Dim StudentCourseGrade As String
'Students---------------------------------------------
For Each stu In studentList.SelectedItems
StudentCourseGrade = "(student='" & stu & "'"
For Each crs In courselist.SelectedItems
StudentCourseGrade = StudentCourseGrade & " AND course = '" & crs & "'"
For Each grd In gradeList.SelectedItems
StudentCourseGrade = StudentCourseGrade & " AND grade = '" & crs & "'"
Next
Next
StudentCourseGrade = StudentCourseGrade & ")"
If WhereClause.Length = 0 Then
WhereClause = "WHERE " & StudentCourseGrade
Else
WhereClause = " OR " & StudentCourseGrade
End If
Next
'Students---------------------------------------------
Dim SQL As String = defaultSQL & WhereClause
da = New OleDb.OleDbDataAdapter(sql, con)
da.Fill(ds, "topclass")
Dim view1 As New DataView(tables(0))
source1.DataSource = view1
DataGridView1.DataSource = view1
DataGridView1.Refresh()
DataGridView1.DataSource = view1
DataGridView1.Refresh()
Dim cnt As Integer
cnt = DataGridView1.Rows.Count
TextBox1.Text = cnt - 1
Dim dayclass As String = TextBox1.Text
TextBox8.Text = dayclass
con.Close()
End Sub
Hth
Chicken

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

Converting a OleDbDataReader to a String to display a COUNT command in List View

I want to display in a ListView the COUNT of a specific Employee Name whilst using two MS Access queries. The COUNT that is being displayed is only 0, 1 or 2 but there are many none "----" values in the database.
The command is binded to a RadioButton:
Private Sub RadioButton2_Click(sender As Object, e As EventArgs) Handles RadioButton2.Click
Dim con As New OleDbConnection("PROVIDER=Microsoft.Jet.OLEDB.4.0;Data Source=" & Application.StartupPath & "\sheetlog.mdb;Jet OLEDB:Database Password = 'password';")
con.Open()
Dim try2 As String = "----"
Dim try3 As String
Dim oledbCmd, oledbCmd2 As OleDbCommand
Dim cmd, cmd2 As String
cmd = "SELECT DISTINCT empname FROM sheet"
oledbCmd = New OleDbCommand(cmd, con)
Dim oledbReader As OleDbDataReader = oledbCmd.ExecuteReader()
ListView1.Clear()
ListView1.GridLines = True
ListView1.FullRowSelect = True
ListView1.View = View.Details
ListView1.MultiSelect = False
ListView1.Columns.Add("Employee Name", 130)
ListView1.Columns.Add("New", 80)
ListView1.Columns.Add("Rev1", 80)
ListView1.Columns.Add("Rev2", 80)
ListView1.Columns.Add("Rev3", 80)
ListView1.Columns.Add("Rev4", 80)
ListView1.Columns.Add("Rev5", 80)
While (oledbReader.Read)
try3 = oledbReader("empname").ToString
cmd2 = "SELECT count(new) AS cnew, count(rev1) AS crev1, count(rev2) AS crev2, count(rev3) AS crev3, count(rev4) AS crev4, count(rev5) AS crev5 FROM sheet WHERE empname = '" & try3 & "' AND rev1 <> '" & try2 & "' AND rev2 <> '" & try2 & "' AND rev3 <> '" & try2 & "' AND rev4 <> '" & try2 & "' AND rev5 <> '" & try2 & "'"
oledbCmd2 = New OleDbCommand(cmd2, con)
Dim oledbReader2 As OleDbDataReader = oledbCmd2.ExecuteReader()
While (oledbReader2.Read)
With ListView1.Items.Add(oledbReader("empname"))
.subitems.add(oledbReader2("cnew"))
.subitems.add(oledbReader2("crev1"))
.subitems.add(oledbReader2("crev2"))
.subitems.add(oledbReader2("crev3"))
.subitems.add(oledbReader2("crev4"))
.subitems.add(oledbReader2("crev5"))
End With
End While
End While
con.Close()
End Sub
I've been away from VB.NET for a bit, but I think you need to do While(oledbReader2.Read())for the second DataReader:
Dim oledbReader2 As OleDbDataReader = oledbCmd2.ExecuteReader()
' I think you need this here:
While (oledbReader2.Read)
With ListView1.Items.Add(oledbReader("empname"))
.subitems.add(oledbReader2("cnew"))
.subitems.add(oledbReader2("crev1"))
.subitems.add(oledbReader2("crev2"))
.subitems.add(oledbReader2("crev3"))
.subitems.add(oledbReader2("crev4"))
.subitems.add(oledbReader2("crev5"))
End With
End While

da.fill incorrect syntax near ')'

I'm having a problem from the line
da.Fill(ds, "Employee")
and I don't have any clue to solve this. Can anyone help?
This is my actual code:
Private Sub btnsearch_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnsearch.Click
Dim da As New SqlClient.SqlDataAdapter
Dim ds As New DataSet
Dim dt As New DataTable
If txtssn.Text = "" Then
MsgBox("Please input SSN.", MsgBoxStyle.Exclamation, "Company Records - Employee")
Else
con.Open()
Dim cmd As New SqlCommand("SELECT * FROM [Employee] WHERE [Ssn] = '" & Trim(Me.txtssn.Text) & "')", con)
da.SelectCommand = cmd
da.Fill(ds, "Employee")
dt = ds.Tables("Employee")
If (dt.Rows.Count > 0) Then
Me.txtfname.Text = dt.Rows(0).Item(1)
Me.txtmi.Text = dt.Rows(0).Item(2)
Me.txtlname.Text = dt.Rows(0).Item(3)
Me.dtpbdate.Text = dt.Rows(0).Item(5)
Me.txtaddress.Text = dt.Rows(0).Item(6)
Me.cmbsex.Text = dt.Rows(0).Item(7)
Me.txtsalary.Text = dt.Rows(0).Item(8)
Me.cmbsuperssn.Text = dt.Rows(0).Item(9)
'Me.cmbdept.Text =
btnedit.Enabled = True
btndelete.Enabled = True
editable()
Else
MsgBox("Record Not Found", MsgBoxStyle.Information + MsgBoxStyle.OkOnly, "Company Records - Employee")
End If
con.Close()
End If
Remove the closing parantheses since that's a SELECT not an INSERT:
"SELECT * FROM [Employee] WHERE [Ssn] = '" & Trim(Me.txtssn.Text) & "'"
However, i would always use sql-parameters to prevent sql-injection.
Using con As New SqlConnection("ConenctionString")
Using da As New SqlDataAdapter("SELECT * FROM [Employee] WHERE [Ssn] = #SSN", con)
da.SelectCommand.Parameters.Add("#SSN", SqlDbType.VarChar).Value = txtssn.Text
da.Fill(ds, "Employee")
End Using
End Using
Remove the trailing ) from your SQL statement.
"SELECT * FROM [Employee] WHERE [Ssn] = '" & Trim(Me.txtssn.Text) & "'"
Also see why you shouldn't be doing it in the first place.
Their is syntax error near your SQLstatement so you need to remove an unwanted ( to make this statement workable.
Dim cmd As New SqlCommand("SELECT * FROM [Employee] WHERE [Ssn] = '" & Trim(Me.txtssn.Text) & "'", con)

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

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.