<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="RetrieveIdentity" %>
Inserting data and retrieving Identity value using Stored Procedures
File: Default.aspx.cs
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
public partial class RetrieveIdentity : System.Web.UI.Page
{
protected void btnAdd_Click(object sender, EventArgs e)
{
string connString = ConfigurationManager.ConnectionStrings["Book"].ConnectionString;
SqlConnection conn = new SqlConnection(connString);
try
{
conn.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandText = "CreatePublisher";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@pubName", txtName.Text);
SqlParameter param = new SqlParameter();
param.ParameterName = "@pubId";
param.Size = 4;
param.SqlDbType = SqlDbType.Int;
param.Direction = ParameterDirection.Output;
cmd.Parameters.Add(param);
int nrows = cmd.ExecuteNonQuery();
string msg = nrows + " row was added
";
int id = (int)param.Value;
msg += "PublisherId of new record=" + id;
labMsg.Text = msg;
conn.Close();
}
catch (Exception ex)
{
labMsg.Text = "Error occurred accessing the database";
labMsg.Text += "
" + ex.Message;
}
finally
{
conn.Close();
}
}
}