Search This Blog

Saturday 28 February 2015

How to return Output parameter from Stored Procedure in ASP.Net using C#

Step 1:- Create table

create table EmpTable
(
       EmpId int identity,
       EmpName varchar(50)
)

Step 2:- Create Procedure

create proc  getOutputValue
@EmpName varchar(50),
@LastIdentity int output
as
begin
       insert into EmpTable(EmpName)
       values(@EmpName)

       set @LastIdentity = @@identity
end

Step 3:- Get output parameter value in SQL Server

declare @LastIdentity int
exec getOutputValue 'Employee 4', @LastIdentity output
print @LastIdentity


Step 4:- Get output parameter value in ASP.Net using C#

Step 1:- Default.aspx Code

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="Demo.Default" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <asp:TextBox ID="txtEmpName" runat="server"></asp:TextBox>
            <br />
            <asp:Button ID="btnGetOutputValue" runat="server" Text="Get Output Value" OnClick="btnGetOutputValue_Click" />
            <br />
            <asp:Label ID="lblMsg" runat="server" Text=""></asp:Label>
        </div>
    </form>
</body>
</html>

Step 2:- Default.aspx.cs Code

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Demo
{
    public partial class Default : System.Web.UI.Page
    {

        protected void Page_Load(object sender, EventArgs e)
        {
        }
        protected void btnGetOutputValue_Click(object sender, EventArgs e)
        {
            SqlConnection con = new SqlConnection(@"server=192.168.1.1; database=TEST; uid=sa; pwd=admin@123;");
            SqlCommand com = new SqlCommand();
            com.CommandText = "getOutputValue";
            com.CommandType = CommandType.StoredProcedure;
            com.Parameters.AddWithValue("@EmpName", txtEmpName.Text);
            com.Parameters.Add("@LastIdentity",SqlDbType.Int);
            com.Parameters["@LastIdentity"].Direction = ParameterDirection.Output;
            com.Connection = con;
            con.Open();
            com.ExecuteNonQuery();
            con.Close();

            lblMsg.Text = "Last Identity " + com.Parameters["@LastIdentity"].Value;
        }
    }
}

No comments:

Post a Comment