我知道为什么会出现错误“'InvalidArgument =值'0'对于'索引'无效。参数名称:索引'”这是因为我的sql语句未返回任何值。问题是我如何对vb.net进行编程,因此,如果没有值,我将不会遇到该问题。
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
答案 0 :(得分:1)
再次在数据库中检查class_student.classid的数据类型。我已经按照您的指导,将VarChar用作数据类型,但是当我看到ID时,我认为是Long或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
答案 1 :(得分:0)
and也是一种很好的方法,可以先测试它是否不是“无”,然后检查该值;
if queryStr isnot nothing andalso queryStr.lenght > 0 then
除非满足第一个条件,否则if语句的第二部分在andalso之后将不进行评估。因此,如果什么都没有,就不会创建运行时错误...