using System;
using
System.Collections.Generic;
using
System.Linq;
using
System.Web;
using
System.Web.UI;
using
System.Web.UI.WebControls;
using
Utilities;
using
System.Data;
using
System.Data.SqlClient;
namespace Database
{
public partial class IdentityFieldExample : System.Web.UI.Page
{
protected void
Page_Load(object sender, EventArgs e)
{
}
protected void
btnAddCustomer_Click(object sender,
EventArgs e)
{
if (txtName.Text == "")
{
lblDisplay.Text = "You need to enter a customer's name!";
}
else
{
DBConnect objDB = new DBConnect();
SqlCommand objCommand = new SqlCommand();
objCommand.CommandType =
CommandType.StoredProcedure;
objCommand.CommandText = "StoreAirlineCustomer";
// Create
a return parameter that is used by the stored procedure to return output
// using
the return statement.
SqlParameter parameter = new SqlParameter("returnValue",
SqlDbType.Int);
parameter.Direction =
ParameterDirection.ReturnValue;
objCommand.Parameters.Add(parameter);
// Create
an input parameter for the customer's name.
parameter = new SqlParameter("@customerName",
txtName.Text);
objCommand.Parameters.Add(parameter);
objDB.DoUpdateUsingCmdObj(objCommand);
// Get
the return value and display the newly created identity value for the CustomerID
// The
identity value is a value created by the database for this field.
String customerID =
objCommand.Parameters["returnValue"].Value.ToString();
lblDisplay.Text = "The account was successfully created. Here is your
AccountID: " + customerID;
// The
following methods will only work with a live database session. The DBConnect
class methods open and close
// the
database connection as needed when working with strings.
// Method
1: Retrieves the value of the Identity field for the most recently added
record.
// strSQL
= "SELECT @@Identity AS AccountNum";
//
objDB.GetDataSet(strSQL);
//
lblDisplay.Text = "The account was successfully created. Here is your
AccountID: " + objDB.GetField("AccountNum", 0);
// Method
2: Utilizes the current DB session and retrieves the value of the Identity
field
// for
the newly added record.
//strSQL
= "SELECT SCOPE_IDENTITY() AS AccountNum";
//objDB.GetDataSet(strSQL);
//lblDisplay.Text
= "The account was successfully created. Here is your AccountID: " +
objDB.GetField("AccountNum", 0);
}
}
}
}