我正在创建一个发票窗口表单应用,但是当我将GetInt32
放在代码中时,我遇到了问题:
private void StoreData()
{
int invoiceID;
int Item_Id;
int quantity;
using (var con = new SqlConnection(@"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\oo\Documents\Data.mdf;Integrated Security=True;Connect Timeout=30"))
{
con.Open();
using (var cmd = con.CreateCommand())
{
cmd.CommandText = @"insert into Invoice(subtotal,tax,total) values (@subtotal,@tax,@total); select SCOPE_IDENTITY() as InvoiceID;";
cmd.Parameters.AddWithValue("@subtotal", subtotal);
cmd.Parameters.AddWithValue("@tax", totalTaxes);
cmd.Parameters.AddWithValue("@total", total);
using (var reader = cmd.ExecuteReader())
{
if (reader.Read())
invoiceID = cmd.GetInt("InvoiceID");
//invoiceID =(int)cmd.Parameters["@InvoiceID"].Value;
}
}
foreach (var item in OrderItems.Rows)
{
using (var cmd = con.CreateCommand())
{
cmd.CommandText = @"insert into InvoiceItem(InvoiceID,ItemID,quantity) values (@InvoiceID,@ItemID,@quantity);";
cmd.Parameters.AddWithValue("@InvoiceID", invoiceID);
cmd.Parameters.AddWithValue("@ItemID", Item_Id);
cmd.Parameters.AddWithValue("@quantity", quantity);
cmd.ExecuteNonQuery();
}
}
}
}
我尝试了invoiceID = cmd.SqlDataReader.GetInt32("InvoiceID");
和invoiceID = cmd.SqlDataReader.GetInt32("InvoiceID");
,但无效。
答案 0 :(得分:1)
GetInt32
期望列的序号位置。要改为指定列名,可以使用SqlDataReader
上的string indexer,invoiceID = (int)reader["InvoiceID"];
接受列名:
InvoiceID
这假定您的GetOrdinal
列不可为空。如果是,则应使用IsDBNull
和{{1}}代替。