我正在处理用户从gridview中选择的项目,并执行电子邮件和数据库插入操作。
当用户选择一个按钮时,下面的代码从gridview中获取信息,在Order表中创建一个新订单,并在Transactions表中创建新条目。
如果使用这种插入记录的方法,如何获取最后插入的ID?您会为这个简单的问题推荐其他方法吗?
protected void btnOrder_Click(object sender, EventArgs e) { double Total = 0; string MailFrom = "webadmin@domain.com"; string MailTo = "purchasing@domain.com"; string MailSubject = "Online Order"; string MailCC = ""; string MailBCC = ""; string MailReplyTo = ""; string MailBody = ""; TextBox ItmCostCode = (TextBox)form1.FindControl("txtCostCode"); foreach (GridViewRow gvr in GridView1.Rows) { CheckBox cb = (CheckBox)gvr.FindControl("ItemSelect"); Label ItmTotal = (Label)gvr.FindControl("ItmTotal"); Label ItmPrice = (Label)gvr.FindControl("ItmPrice"); Label ItmName = (Label)gvr.FindControl("lblName"); TextBox ItmQty = (TextBox)gvr.FindControl("ItmQty"); TextBox ItmID = (TextBox)gvr.FindControl("lblItemID"); //Add entry to Order Table SqlDataSource2.InsertParameters.Add("OrderDate", DateTime.Now.ToString("MMMM dd, yyyy")); SqlDataSource2.InsertParameters.Add("OrderTotal", "0"); SqlDataSource2.InsertParameters.Add("OrderAccount", "name"); SqlDataSource2.InsertParameters.Add("OrderCostCentre", ItmCostCode.Text); SqlDataSource2.Insert(); //TODO: GET ORDERID HERE TO USE BELOW: if (cb.Checked) { double Price = Convert.ToDouble(ItmPrice.Text); double Qty = Convert.ToDouble(ItmQty.Text); Total = Price * Qty; OrderTotal = OrderTotal + Total; MailBody = MailBody + "Item: "+ItmName.Text+" Quantity: "+ItmQty.Text+" Total: "+ItmTotal.Text+"\n\r"; //Add entry to Transaction Table SqlDataSource3.InsertParameters.Add("ItemID", ItmID.Text); SqlDataSource3.InsertParameters.Add("OrderID", ); SqlDataSource3.InsertParameters.Add("Price", ItmPrice.Text); SqlDataSource3.Insert(); } //TODO: Update Order table with OrderTotal } string strOrderTotal = OrderTotal.ToString(); MailBody = MailBody+"Order Total: " + strOrderTotal+"\n\r"; MailBody = MailBody + "Cost Code: " + ItmCostCode.Text; MailService.Service1 Mailer = new MailService.Service1(); Mailer.SendMail("Text", MailFrom, MailTo, MailCC, MailBCC, MailSubject, MailBody, MailReplyTo); }
在插入查询的末尾使用作用域标识,它将返回插入的ID,例如…
INSERT INTO table (ColumnName) VALUES (); GO SELECT SCOPE_IDENTITY();
编辑: 为您的帮助,这是一些可以帮助您实施的文章
http://msdn.microsoft.com/en- us/library/z72eefad.aspx
http://www.mikesdotnetting.com/Article/54/Getting-the-identity-of-the-most- recently-add-record-记录 http://www.objectreference.net/post/SCOPE_IDENTITY()-return-the插入数据库中的- id