Reputation: 15
I know why I am getting the error "'InvalidArgument=Value of '0' is not valid for 'index'.Parameter name: index'" Its because of my sql statement not returning any values. The problem is how I do program vb.net so if there is no values I am not going to run into that problem.
Private Sub showdata1()
Dim queryStr As String = "SELECT student.id,firstname,lastname FROM Student INNER JOIN Class_Student ON student.id = class_student.ID where class_student.classid=" & ListView1.SelectedItems(0).SubItems(0).Text & ""
Dim con As New OleDbConnection("provider=microsoft.jet.oledb.4.0;data source=C:\Users\XXXX\XXXX\XXX\XXX.mdb")
con.Open()
Dim cmd As OleDbCommand = New OleDbCommand(queryStr, con)
Dim read As OleDbDataReader = cmd.ExecuteReader()
If queryStr = "" Then
Else
While read.Read()
Dim item As ListViewItem = New ListViewItem()
item.Text = CStr(read.Item("StudentId"))
item.SubItems.Add(read.Item("FirstName"))
item.SubItems.Add(read.Item("LastName"))
ListView2.Items.Add(item)
End While
End If
con.Close()
End Sub
Upvotes: 0
Views: 1141
Reputation: 15091
Double check in your database for the datatype of class_student.classid. I have followed your lead and used VarChar as datatype but when I see ID I think Long or Interger.
Private Sub showdata1()
'Thanks to Lectere and Hans Passant
If ListView1.SelectedItems.Count = 0 OrElse String.IsNullOrEmpty(ListView1.SelectedItems(0).SubItems(0).Text) Then
Return
End If
'It is OK to use parameter names with OleDB and I think it makes the code clearer.
'Just remember that the additions to the parameters collection must be in the same
'order as they appear in the query.
Dim queryStr As String = "SELECT student.id,firstname,lastname
FROM Student
INNER JOIN Class_Student ON student.id = class_student.ID
WHERE class_student.classid= @ClassID;"
Using con As New OleDbConnection("provider=microsoft.jet.oledb.4.0;data source=C:\Users\XXXX\XXXX\XXX\XXX.mdb")
Using cmd As OleDbCommand = New OleDbCommand(queryStr, con)
cmd.Parameters.Add("@ClassID", OleDbType.VarChar).Value = ListView1.SelectedItems(0).SubItems(0).Text
con.Open()
Using read As OleDbDataReader = cmd.ExecuteReader()
While read.Read()
Dim item As New ListViewItem()
item.Text = CStr(read.Item("StudentId"))
item.SubItems.Add(CStr(read.Item("FirstName")))
item.SubItems.Add(CStr(read.Item("LastName")))
ListView1.Items.Add(item)
End While
End Using 'Close and dispose reader
End Using 'Close and dispose command
End Using 'Close and dispose connection
End Sub
Upvotes: 1
Reputation: 1547
The andalso is a good way to first test if it's not 'nothing', and then check the value;
if queryStr isnot nothing andalso queryStr.lenght > 0 then
The second part of the if statement, after andalso, will not be evaluated unless the first condition is met. Thus not creating a runtime error if it's nothing...
Upvotes: 0