Mega Code Archive

 
Categories / ASP.Net Tutorial / ADO Net Database
 

Use SQL Server stored procedures to insert a new record and then retrieve the identity value

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs"  Inherits="RetrieveIdentity" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head id="Head1" runat="server">    <title>Inserting data and retrieving Identity value using Stored Procedures</title> </head> <body>    <form id="form1" runat="server">       <div id="container">       <h2>Enter a new publisher</h2>       <asp:TextBox ID="txtName" runat="server" /><br />       <asp:Button ID="btnAdd" runat="server" Text="Add Publisher" OnClick="btnAdd_Click" />                 <asp:Label ID="labMsg" runat="server" />                         </div>    </form> </body> </html> 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<br/>";          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 += "<br/>" + ex.Message;       }       finally       {          conn.Close();       }    } }