cast is invalid when attempting to grab inserted ID
I am attempting to grab the recently inserted ID for a table, but I keep receiving a casting error. The item always contains NULL, and I am not sure why. I am following the instructions located here: http://www.mikesdotnetting.com/Article/54/Getting-the-identity-of-the-most-recently-added-record
Here is my SqlDataSource:
<asp:SqlDataSource ID="SqlDataSource2" runat="server"
ConnectionString="<%$ ConnectionStrings:NH_SWAGConnectionString %>"
InsertCommand="INSERT INTO [tblOrders] ([OrderDate], [OrderTotal], [OrderAccount], [OrderCostCentre]) VALUES (@OrderDate, @OrderTotal, @OrderAccount, @OrderCostCentre); SET @OrderNewID = SCOPE_IDENTITY()"
SelectCommand="SELECT * FROM [tblOrders]"
UpdateCommand="UPDATE [tblOrders] SET [OrderDate] = @OrderDate, [Order开发者_如何学运维Total] = @OrderTotal, [OrderAccount] = @OrderAccount, [OrderCostCentre] = @OrderCostCentre WHERE [OrderID] = @original_OrderID AND [OrderDate] = @original_OrderDate AND [OrderTotal] = @original_OrderTotal AND [OrderAccount] = @original_OrderAccount AND [OrderCostCentre] = @original_OrderCostCentre"
ConflictDetection="CompareAllValues"
OldValuesParameterFormatString="original_{0}"
OnInserting="SqlDataSource2_Inserting"
OnInserted="SqlDataSource2_Inserted">
<InsertParameters>
<asp:Parameter Direction="Output" Name="OrderNewId" Type="Int32" />
</InsertParameters>
<UpdateParameters>
<asp:Parameter Name="OrderDate" Type="DateTime" />
<asp:Parameter Name="OrderTotal" Type="Decimal" />
<asp:Parameter Name="OrderAccount" Type="String" />
<asp:Parameter Name="OrderCostCentre" Type="String" />
<asp:Parameter Name="original_OrderID" Type="Int32" />
<asp:Parameter Name="original_OrderDate" Type="DateTime" />
<asp:Parameter Name="original_OrderTotal" Type="Decimal" />
<asp:Parameter Name="original_OrderAccount" Type="String" />
<asp:Parameter Name="original_OrderCostCentre" Type="String" />
</UpdateParameters>
</asp:SqlDataSource>
Here is the code behind inserting the new record, and calling SCOPE_IDENTITY()
to grab the new ID:
protected void btnOrder_Click(object sender, EventArgs e)
{
//Add entry to Order Table
SqlDataSource2.InsertParameters.Add("OrderDate", DateTime.Now.ToString("MMMM dd, yyyy"));
SqlDataSource2.InsertParameters.Add("OrderTotal", "0");
SqlDataSource2.InsertParameters.Add("OrderAccount", ItmUser);
SqlDataSource2.InsertParameters.Add("OrderCostCentre", ItmCostCode.Text);
SqlDataSource2.Insert();
}
protected void SqlDataSource2_Inserted(object sender, SqlDataSourceStatusEventArgs e)
{
OrderNewID = (int)e.Command.Parameters["@OrderNewId"].Value;
}
Why @OrderNewId
above is NULL?
Ok I got it figured. Instead of using SET I used SELECT in the InsertQuery:
INSERT INTO [tblOrders] ([OrderDate], [OrderTotal], [OrderAccount], [OrderCostCentre]) VALUES (@OrderDate, @OrderTotal, @OrderAccount, @OrderCostCentre); SELECT @OrderNewID = SCOPE_IDENTITY()
精彩评论