Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people, just like you, are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
Solved

Getting Scope_Identity / Output Value from Stored Procedure

Posted on 2011-03-14
7
728 Views
Last Modified: 2012-05-11
Hello,
I am not able to extract the value of an output parameter. I am using an objectDataSource that references a SQL Stored Procedure. The error I get is "Object reference not set to an instance of an object."

here is the codebehind that fires the error
   protected void WorkOrderDataSource_Inserted(object sender, ObjectDataSourceStatusEventArgs e)
    {
        if (e.Exception == null)
        {
            FeedbackText.Text = e.OutputParameters["@WorkOrderID"].ToString();
        }
    }

Open in new window

BLL
    public static DataTable WorkOrderInsert(int WorkOrderID, string CustomerFirstName,
     string CustomerLastName, string CustomerPhone, string WorkDescription, 
     int DepartmentID, string DepartmentPhone, int LocationID, string LocationType, 
     string RPFirstName, string RPLastName, string RPEmail, string RPApprovalDate,
     string PMFirstName, string PMLastName, string PMEmail, string PMApprovalDate)
    {
        DataTable WorkOrderData = new DataTable();
        SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionAIMDB"].ConnectionString);

        //must check for null parameters
        if (CustomerFirstName == null) { CustomerFirstName = String.Empty; }
        if (CustomerLastName == null) { CustomerLastName = String.Empty; }
        if (CustomerPhone == null) { CustomerPhone = String.Empty; }
        if (WorkDescription == null) { WorkDescription = String.Empty; }
        if (DepartmentPhone == null) { DepartmentPhone = String.Empty; }
        if (LocationType == null) { LocationType = String.Empty; }
        if (RPFirstName == null) { RPFirstName = String.Empty; }
        if (RPLastName == null) { RPLastName = String.Empty; }
        if (RPEmail == null) { RPEmail = String.Empty; }
        if (RPApprovalDate == null) { RPApprovalDate = String.Empty; }
        if (PMFirstName == null) { PMFirstName = String.Empty; }
        if (PMLastName == null) { PMLastName = String.Empty; }
        if (PMEmail == null) { PMEmail = String.Empty; }
        if (PMApprovalDate == null) { PMApprovalDate = String.Empty; }


        try
        {
            SqlCommand cmd = new SqlCommand("WorkOrderInsert", connection);

            //create parameters
            //cmd.Parameters.AddWithValue("@WorkOrderID", WorkOrderID);
            cmd.Parameters.Add("@WorkOrderID", SqlDbType.Int);
            cmd.Parameters["@WorkOrderID"].Direction = ParameterDirection.Output;
            cmd.Parameters.AddWithValue("@CustomerFirstName", CustomerFirstName);
            cmd.Parameters.AddWithValue("@CustomerLastName", CustomerLastName);
            cmd.Parameters.AddWithValue("@CustomerPhone", CustomerPhone);
            cmd.Parameters.AddWithValue("@WorkDescription", WorkDescription);
            cmd.Parameters.AddWithValue("@DepartmentID", DepartmentID);
            cmd.Parameters.AddWithValue("@DepartmentPhone", DepartmentPhone);
            cmd.Parameters.AddWithValue("@LocationID", LocationID);
            cmd.Parameters.AddWithValue("@LocationType", LocationType);
            cmd.Parameters.AddWithValue("@RPFirstName", RPFirstName);
            cmd.Parameters.AddWithValue("@RPLastName", RPLastName);
            cmd.Parameters.AddWithValue("@RPEmail", RPEmail);
            cmd.Parameters.AddWithValue("@RPApprovalDate", RPApprovalDate);
            cmd.Parameters.AddWithValue("@PMFirstName", PMFirstName);
            cmd.Parameters.AddWithValue("@PMLastName", PMLastName);
            cmd.Parameters.AddWithValue("@PMEmail", PMEmail);
            cmd.Parameters.AddWithValue("@PMApprovalDate", PMApprovalDate);

            cmd.CommandType = CommandType.StoredProcedure;

            connection.Open();
            SqlDataAdapter adapter = new SqlDataAdapter(cmd);
            adapter.Fill(WorkOrderData);
            connection.Close();

        }
        catch
        {
            connection.Close();
        }
        return WorkOrderData;
    }

Open in new window

and finally the markup
    <asp:UpdatePanel ID="MainUpdatePanel" runat="server">
        <ContentTemplate>
            <div class="exampleWrapper">
                <div style="float: left; width: 600px">
                    <asp:Wizard ID="wzd" runat="Server" Width="100%" DisplaySideBar="False" BackColor="#F7F6F3"
                        BorderColor="#CCCCCC" BorderStyle="Solid" BorderWidth="1px" Font-Names="Verdana"
                        Font-Size="0.8em" OnActiveStepChanged="wzd_ActiveStepChanged" ActiveStepIndex="3">
                        <HeaderStyle BackColor="#5D7B9D" BorderStyle="Solid" Font-Bold="True" Font-Size="0.9em"
                            ForeColor="White" HorizontalAlign="Left" />
                        <HeaderTemplate>
                            <table style="width: 100%" cellpadding="0" cellspacing="0">
                                <tr>
                                    <td class="wizardTitle">
                                        <%= wzd.ActiveStep.Title%>
                                    </td>
                                    <td>
                                        <table style="width: 100%; border-collapse: collapse;">
                                            <tr>
                                                <td style="text-align: right">
                                                    <span class="wizardProgress">Steps:</span>
                                                </td>
                                                <asp:Repeater ID="SideBarList" runat="server">
                                                    <ItemTemplate>
                                                        <td class="stepBreak">
                                                            &nbsp;
                                                        </td>
                                                        <td class="<%# GetClassForWizardStep(Container.DataItem) %>" title="<%# DataBinder.Eval(Container, "DataItem.Name")%>">
                                                            <%# wzd.WizardSteps.IndexOf(Container.DataItem as WizardStep) + 1 %>
                                                        </td>
                                                    </ItemTemplate>
                                                </asp:Repeater>
                                            </tr>
                                        </table>
                                    </td>
                                </tr>
                            </table>
                        </HeaderTemplate>
                        <NavigationButtonStyle BackColor="#FFFBFF" BorderColor="#CCCCCC" BorderStyle="Solid"
                            BorderWidth="1px" Font-Names="Verdana" Font-Size="0.8em" ForeColor="#284775" />
                        <SideBarButtonStyle BorderWidth="0px" Font-Names="Verdana" ForeColor="White" />
                        <SideBarStyle BackColor="#7C6F57" BorderWidth="0px" Font-Size="0.9em" VerticalAlign="Top" />
                        <SideBarTemplate>
                        </SideBarTemplate>
                        <StepStyle BorderWidth="0px" ForeColor="#5D7B9D" />
                        <WizardSteps>
                            <asp:WizardStep runat="server">
                                <div class="stepWrapper">
                                    <ucUserInfo:UserInfo ID="userinfoControl" runat="server" />
                                </div>
                            </asp:WizardStep>
                            <asp:WizardStep runat="server">
                                <div class="stepWrapper">
                                    <ucWorkOrder:WorkOrder ID="workorderControl" runat="server" />
                                </div>
                            </asp:WizardStep>
                            <asp:WizardStep runat="server">
                                <div class="stepWrapper">
                                    <ucApprovals:Approvals ID="approvalsControl" runat="server" />
                                </div>
                            </asp:WizardStep>
                            <asp:WizardStep runat="server" StepType="Complete">
                                <div class="stepWrapper">
                                    <div align="center">
                                        <asp:ObjectDataSource ID="WorkOrderDataSource" runat="server" InsertMethod="WorkOrderInsert"
                                            TypeName="WorkOrderBLL" OnInserted="WorkOrderDataSource_Inserted">
                                            <InsertParameters>
                                                <asp:Parameter Direction="Output" Name="WorkOrderID" Type="Int32" />
                                                <asp:ControlParameter ControlID="userInfoControl" Name="CustomerFirstName" PropertyName="CustomerFirstName"
                                                    Direction="Input" Type="String" />
                                                <asp:ControlParameter ControlID="userInfoControl" Name="CustomerLastName" PropertyName="CustomerLastName"
                                                    Direction="Input" Type="String" />
                                                <asp:ControlParameter ControlID="userInfoControl" Name="CustomerPhone" PropertyName="CustomerPhone"
                                                    Direction="Input" Type="String" />
                                                <asp:ControlParameter ControlID="workorderControl" Name="WorkDescription" PropertyName="WorkDescription"
                                                    Direction="Input" Type="String" />
                                                <asp:ControlParameter ControlID="workorderControl" Name="DepartmentID" PropertyName="Department"
                                                    Direction="Input" Type="Int32" />
                                                <asp:ControlParameter ControlID="workorderControl" Name="DepartmentPhone" PropertyName="DepartmentPhone"
                                                    Direction="Input" Type="String" />
                                                <asp:ControlParameter ControlID="workorderControl" Name="LocationID" PropertyName="Address"
                                                    Direction="Input" Type="Int32" />
                                                <asp:ControlParameter ControlID="workorderControl" Name="LocationType" PropertyName="LocationType"
                                                    Direction="Input" Type="String" />
                                                <asp:ControlParameter ControlID="approvalsControl" Name="RPFirstName" PropertyName="RPFirstName"
                                                    Direction="Input" Type="String" />
                                                <asp:ControlParameter ControlID="approvalsControl" Name="RPLastName" PropertyName="RPLastName"
                                                    Direction="Input" Type="String" />
                                                <asp:ControlParameter ControlID="approvalsControl" Name="RPEmail" PropertyName="RPEmail"
                                                    Direction="Input" Type="String" />
                                                <asp:ControlParameter ControlID="approvalsControl" Name="RPApprovalDate" PropertyName="RPApprovalDate"
                                                    Direction="Input" Type="String" />
                                                <asp:ControlParameter ControlID="approvalsControl" Name="PMFirstName" PropertyName="PMFirstName"
                                                    Direction="Input" Type="String" />
                                                <asp:ControlParameter ControlID="approvalsControl" Name="PMLastName" PropertyName="PMLastName"
                                                    Direction="Input" Type="String" />
                                                <asp:ControlParameter ControlID="approvalsControl" Name="PMEmail" PropertyName="PMEmail"
                                                    Direction="Input" Type="String" />
                                                <asp:ControlParameter ControlID="approvalsControl" Name="PMApprovalDate" PropertyName="PMApprovalDate"
                                                    Direction="Input" Type="String" />
                                            </InsertParameters>
                                            <SelectParameters>
                                                <asp:Parameter Name="WorkOrderID" Type="Int32" />
                                                <asp:Parameter Name="CustomerFirstName" Type="String" />
                                                <asp:Parameter Name="CustomerLastName" Type="String" />
                                                <asp:Parameter Name="CustomerPhone" Type="String" />
                                                <asp:Parameter Name="WorkDescription" Type="String" />
                                                <asp:Parameter Name="DepartmentID" Type="Int32" />
                                                <asp:Parameter Name="DepartmentPhone" Type="String" />
                                                <asp:Parameter Name="LocationID" Type="Int32" />
                                                <asp:Parameter Name="LocationType" Type="String" />
                                                <asp:Parameter Name="RPFirstName" Type="String" />
                                                <asp:Parameter Name="RPLastName" Type="String" />
                                                <asp:Parameter Name="RPEmail" Type="String" />
                                                <asp:Parameter Name="RPApprovalDate" Type="String" />
                                                <asp:Parameter Name="PMFirstName" Type="String" />
                                                <asp:Parameter Name="PMLastName" Type="String" />
                                                <asp:Parameter Name="PMEmail" Type="String" />
                                                <asp:Parameter Name="PMApprovalDate" Type="String" />
                                            </SelectParameters>
                                        </asp:ObjectDataSource>
                                        <asp:Button ID="SaveButton" runat="server" Text="Save" OnClick="SaveButton_Click">
                                        </asp:Button></div>
                                      
                                </div>
                            </asp:WizardStep>
                        </WizardSteps>
                    </asp:Wizard>
                </div>
                <div class="previewWrapper">
                    <ucPreview:Preview ID="previewControl" runat="server" />
                </div>
            </div>
              <asp:Label ID="FeedbackText" runat="server"></asp:Label>
        </ContentTemplate>
    </asp:UpdatePanel>

Open in new window

and for good measure, my stored procedure
USE [AIM]
GO
/****** Object:  StoredProcedure [dbo].[WorkOrderInsert]    Script Date: 03/14/2011 12:28:07 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		Martin Jordan
-- Create date: 3/9/2011
-- Description:	Insert WorkOrder related information
-- =============================================
ALTER PROCEDURE [dbo].[WorkOrderInsert]
	-- Add the parameters for the stored procedure here
	(   
	   @WorkOrderID int OUTPUT,
       @CustomerFirstName nvarchar(25),
       @CustomerLastName nvarchar(50),
       @CustomerPhone nvarchar(20),
       @WorkDescription nvarchar(4000),
       @DepartmentID int,
       @DepartmentPhone nvarchar(20),
       @LocationID int,
       @LocationType nvarchar(20),
       @RPFirstName nvarchar(25),
       @RPLastName nvarchar(50),
       @RPEmail nvarchar(50),
       @RPApprovalDate date,
       @PMFirstName nvarchar(25),
       @PMLastName nvarchar(50),
       @PMEmail nvarchar(50),
       @PMApprovalDate date
       
     )	
AS
BEGIN TRANSACTION
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

    -- select
		
	-- insert
	INSERT INTO [FAC_WorkOrder] 
	   ([CustomerFirstName],
       [CustomerLastName],
       [CustomerPhone],
       [WorkDescription],
       [DepartmentID],
       [DepartmentPhone],
       [LocationID],
       [LocationType],
       [RPFirstName],
       [RPLastName],
       [RPEmail],
       [RPApprovalDate],
       [PMFirstName],
       [PMLastName],
       [PMEmail],
       [PMApprovalDate])
     VALUES 
       (@CustomerFirstName,
       @CustomerLastName,
       @CustomerPhone,
       @WorkDescription,
       @DepartmentID,
       @DepartmentPhone,
       @LocationID,
       @LocationType,
       @RPFirstName,
       @RPLastName,
       @RPEmail,
       @RPApprovalDate,
       @PMFirstName,
       @PMLastName,
       @PMEmail,
       @PMApprovalDate)
	SET @WorkOrderID = SCOPE_IDENTITY()
	SELECT SCOPE_IDENTITY()
	
	IF @@ERROR <> 0
 BEGIN
    -- Rollback the transaction
    ROLLBACK

    -- Raise an error and return
    RAISERROR ('Error in inserting into FAC_Department.', 16, 1)
    RETURN
 END

COMMIT

Open in new window

been stuck on this for hours, it feels like I'm missing something very obvious and simple

Thank you for your consideration
0
Comment
Question by:dantcho
  • 5
7 Comments
 
LVL 143

Expert Comment

by:Guy Hengel [angelIII / a3]
ID: 35130097
in the procedure , you need 1 more line:

SET  @WorkOrderID = SCOPE_IDENTITY()
0
 

Author Comment

by:dantcho
ID: 35130244
Hmm? That's already in there, did I put it in the wrong place?
0
 
LVL 2

Expert Comment

by:enkor
ID: 35130334
Have you declared the parameter @WorkOrderID?
0
Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

 

Author Comment

by:dantcho
ID: 35130521
yes, i define it in the SP here:          @WorkOrderID int OUTPUT,

in the BLL here:   cmd.Parameters.Add("@WorkOrderID", SqlDbType.Int);
            cmd.Parameters["@WorkOrderID"].Direction = ParameterDirection.Output;

in the markup here: <asp:Parameter Direction="Output" Name="WorkOrderID" Type="Int32" />
0
 

Accepted Solution

by:
dantcho earned 0 total points
ID: 35131774
Going to just switch to using typed datasets instead of writing the BLL and DAL myself, problem goes away when I do so.
0
 

Author Comment

by:dantcho
ID: 35131801
nm
0
 

Author Closing Comment

by:dantcho
ID: 35170987
not doing it this way.. have too little time to wait for someone to pore over my code and suggest where something might be changed.

this is a time sensitive project
0

Featured Post

Networking for the Cloud Era

Join Microsoft and Riverbed for a discussion and demonstration of enhancements to SteelConnect:
-One-click orchestration and cloud connectivity in Azure environments
-Tight integration of SD-WAN and WAN optimization capabilities
-Scalability and resiliency equal to a data center

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Entity Framework is a powerful tool to help you interact with the DataBase but still doesn't help much when we have a Stored Procedure that returns more than one resultset. The solution takes some of out-of-the-box thinking; read on!
The article shows the basic steps of integrating an HTML theme template into an ASP.NET MVC project
This video shows how to use Hyena, from SystemTools Software, to bulk import 100 user accounts from an external text file. View in 1080p for best video quality.
Email security requires an ever evolving service that stays up to date with counter-evolving threats. The Email Laundry perform Research and Development to ensure their email security service evolves faster than cyber criminals. We apply our Threat…

840 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question