我不知道错误是什么。当我在SQL Server或vb.net查询构建器中运行我的SQL语句时,我没有得到任何错误,我得到了结果。但是当我从我的vb.net代码运行它时,我收到了这个错误:
System.IndexOutOfRangeException:发票
在System.Data.ProvideBase.FieldNameLookup.GetORdrinal(String fieldName)
在Suste.mData.SqlClient.SqlDataReader.GetOrdnal(String name)....(更多文本)
这是我的代码:
Private Sub FillPulloutList(employee_id As Integer, transaction_date As Date)
Try
cnn.Open()
query = "SELECT invoice As 'Invoice', product_id As 'Product ID', quantity As 'Quantity', amount As 'Amount', transaction_date As 'Date', employee_id As 'Employee ID' FROM pullouts_tbl " & _
"WHERE (transaction_date = @transaction_date) AND (employee_id = @employee_id)"
cmd.Parameters.AddWithValue("@_transaction_date", transaction_date)
cmd.Parameters.AddWithValue("@_employee_id", employee_id)
dr = cmd.ExecuteReader()
While dr.Read
PulloutListDGV.Rows.Add(dr("Invoice"), dr("Amount"))
End While
Catch ex As Exception
MessageBox.Show(ex.ToString)
Finally
cnn.Close()
End Try
End Sub
我已经在这个程序中使用了这个代码超过一百次我创建但除了这个之外没有任何错误。你能指出我在这里做错了什么吗?谢谢。
这是我的表,如果它有帮助
if not exists (select * from sys.tables where name = N'pullouts_tbl' and type = N'U')
begin
create table pullouts_tbl
(
tid int identity(1,1) not null,
transaction_date date not null,
invoice int not null,
product_id nchar(20) not null,
quantity int not null,
amount decimal(18,2) not null,
employee_id nchar(20) not null
constraint pullouts_tbl_tid_pk primary key clustered (tid)
constraint pullouts_tbl_invoice_fk
foreign key (invoice) references invoice_tbl(invoice),
constraint pullouts_tbl_product_id_fk
foreign key (product_id) references products_tbl(product_id),
constraint pullouts_tbl_employee_id_fk
foreign key (employee_id) references employees_tbl(employee_id)
)
答案 0 :(得分:1)
在我看来问题就在这里:
PulloutListDGV.Rows.Add(dr("Invoice"), dr("Amount"))
在结果集中找不到其中一列或两列。我注意到这两列都是在您分配给query
变量的SQL代码中指定的,但您从未将该SQL分配给CommandText
的{{1}}。您可能正在执行其他一些查询。这是为什么要在使用它时创建命令对象的一个示例。