nice.atma nice.atma - 1 month ago 13
Vb.net Question

Populate listview from access database using another listview in vb.net

I have two listviews,

lvNum
having one column and
lvList
have 8 columns. I want to populate my
lvList
from my access database through my
lvNum
. If I click a row in my
lvNum
, my
lvList
items will be added from the database. If I click once the
lvList
is populated,but when I click another cell it gives me an error


InvalidArgument=Value of '0' is not valid for 'index'.


This is my code to load the record to all my listviews

Public Sub loadRecord(lv As ListView, sql As String, noOfIndex As Integer)
Try
lv.Items.Clear()
Dim lvcmd As OleDbCommand = New OleDbCommand(sql, konek)
Dim lvdr As OleDbDataReader = lvcmd.ExecuteReader

If lvdr.HasRows Then
While lvdr.Read
Dim newLv As New ListViewItem
newLv.Text = lvdr.GetValue(0)
For item As Integer = 1 To noOfIndex
newLv.SubItems.Add(lvdr.GetValue(item))
Next
lv.Items.Add(newLv)
End While
End If
Catch ex As Exception
MsgBox(ex.Message, , "Load Record Error")
End Try
End Sub


I call the sub in the lvNum selectedIndexChanged event

Private Sub lvNum_SelectedIndexChanged(sender As Object, e As EventArgs) Handles lvNum.SelectedIndexChanged
'this is where I get my error
Dim joindRecord As String = "SELECT tblProducts.prodName,tblProducts.prodCode,tblProducts.Description," & _
"tblProducts.prodCost,tblPurchaseOrder.POQty,tblPurchaseOrder.PODiscount, tblPurchaseOrder.total," & _
"tblPurchaseOrder.prodID,tblProducts.prodID,tblPurchaseOrder.PONumber " & _
"FROM tblProducts INNER JOIN tblPurchaseOrder ON tblProducts.prodID = tblPurchaseOrder.prodID " & _
"WHERE tblPurchaseOrder.PONumber ='" & lvNum.SelectedItems.Item(0).Text & "'"

Call loadRecord(lvList, joindRecord, 7)
End Sub

Answer

I figured it out I added this piece of code

If lvPO.SelectedItems.Count <> 0 Then 
 'code goes here
End If

So the code goes like this

Private Sub lvNum_SelectedIndexChanged(sender As Object, e As EventArgs)  Handles lvNum.SelectedIndexChanged
If lvPO.SelectedItems.Count <> 0 Then
   Dim joindRecord As String = "SELECT  tblProducts.prodName,tblProducts.prodCode,tblProducts.Description," & _
    "tblProducts.prodCost,tblPurchaseOrder.POQty,tblPurchaseOrder.PODiscount, tblPurchaseOrder.total," & _
    "tblPurchaseOrder.prodID,tblProducts.prodID,tblPurchaseOrder.PONumber " & _
    "FROM tblProducts INNER JOIN tblPurchaseOrder ON tblProducts.prodID = tblPurchaseOrder.prodID " & _
    "WHERE tblPurchaseOrder.PONumber ='" & lvNum.SelectedItems.Item(0).Text & "'"

   Call loadRecord(lvList, joindRecord, 7)
End If
End Sub