【发布时间】:2016-05-10 02:01:57
【问题描述】:
我在创建用于在数据网格视图中显示项目的搜索查询时遇到了一些问题,我得到的错误是“索引超出范围。必须是非负数并且小于集合的大小。 参数名称:索引"
下面是我的代码:
Try
connect()
Dim sql = "SELECT pcb, component, hour, faultcode, line FROM [sqlcnvfaultentry] WHERE "
If CheckBox_pcb.Checked Then
Sql = Sql & " and pcb = @pcb "
cmd.Parameters.AddWithValue("@pcb", ComboBox_pcb.Text)
End If
If CheckBox_part.Checked Then
Sql = Sql & " and component = @component "
cmd.Parameters.AddWithValue("@component", ComboBox_part.Text)
End If
If CheckBox_hour.Checked Then
Sql = Sql & " and hour = @hour "
cmd.Parameters.AddWithValue("@hour", ComboBox_hour.Text)
End If
If CheckBox_fault.Checked Then
Sql = Sql & " and faultcode = @faultcode "
cmd.Parameters.AddWithValue("@faultcode", ComboBox_fault.Text)
End If
If CheckBox_line.Checked Then
Sql = Sql & " and line = @line "
cmd.Parameters.AddWithValue("@line", ComboBox_line.Text)
End If
Dim adapter = New SqlDataAdapter(cmd.CommandText, con.ConnectionString)
Dim dt As New DataTable()
cmd.CommandText = Sql
adapter.Fill(dt)
DataGridView_c1.DataSource = dt
DataGridView_c1.Refresh()
DataGridView_c1.Columns(0).HeaderText = "PCB:"
DataGridView_c1.Columns(1).HeaderText = "Component:"
DataGridView_c1.Columns(2).HeaderText = "Hour:"
DataGridView_c1.Columns(3).HeaderText = "Fault Code:"
DataGridView_c1.Columns(4).HeaderText = "Line:"
disconnect()
Catch exp As Exception
Throw exp
Finally
End Try
任何帮助都会很棒。
【问题讨论】:
-
哪一行抛出异常?
-
所有字符串连接都将在命令文本的末尾产生
WHERE and blah = @blah。该语法在“where”和“and”之间无效。此外,在您已经从中创建了SqlDataAdapter之后,您正在设置cmd对象的commandText。 -
我已更改“Where 1=1”的代码 - 但引发异常的行是 - DataGridView_c1.Columns(1).HeaderText = "Component:"
-
将
cmd.CommandText = Sql行移动到Dim adapter =位上方的一行。 -
字符串连接会使您面临 SQL 注入和意外错误,无论它是否包含参数占位符。这不是参数化查询。如果你真的需要这样一个开放式查询,使用支持LINQ的ORM(例如EF,NH)并动态添加
.Where(...)子句
标签: mysql vb.net visual-studio