Hi.
i have written a stored procedure in sqlserver:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
Create procedure [dbo].[Insert_Person_SP]
(
@CityId int ,
@Name nvarchar(100),
@Family nvarchar(100),
@Gender nchar(10),
@MilitaryStatus nvarchar(50)
)
as
begin
insert into Person (CityId,Name,Family,Gender,MilitaryStatus)
values (@CityId,@Name,@Family,@Gender,@MilitaryStatus)
return @@Identity
end
and also i have made a class in Asp.net for retrieving PersonId as below:
public class globalvaribles
{
public static int PersonId
{
get
{
if (HttpContext.Current.Session["PersonId"] == null)
HttpContext.Current.Session["PersonId"] = -1;
return int.Parse(HttpContext.Current.Session["PersonId"].ToString());
}
set
{
HttpContext.Current.Session["PersonId"] = value;
}
}
}
and finally in my main code i intend to insert data into DB:
protected void SubmitButton(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection();
SqlTransaction trans = null;
conn.ConnectionString = ConfigurationManager.ConnectionStrings["PersonTest"].ConnectionString;
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
conn.Open();
trans = cmd.Connection.BeginTransaction();
try
{
int pcode = 0;
int.TryParse(DropCity.SelectedValue, out pcode);
cmd.CommandText = "Insert_Person_SP";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("@Name", SqlDbType.NVarChar).Value = textbox1.Text;
cmd.Parameters.Add("@Family", SqlDbType.NVarChar).Value = TextBox2.Text;
cmd.Parameters.Add("@CityId", SqlDbType.Int).Value = DropCity.SelectedValue;
cmd.Parameters.Add("@Gender", SqlDbType.NChar).Value = RadioGender.SelectedValue;
cmd.Parameters.Add("@MilitaryStatus", SqlDbType.NVarChar).Value = DropDownMilitary.SelectedValue;
trans.Commit();
globalvaribles.PersonId = int.Parse(cmd.ExecuteScalar().ToString());
}
catch (SqlException se)
{
try
{
trans.Rollback();
}
catch{ }
Page.Title = "SqlException:" + se.Message;
try
{
trans.Rollback();
}
catch (Exception ex)
{
Page.Title = "Exception:" + ex.Message;
}
}
finally
{
try
{
conn.Close();
}
catch { }
}
Response.Redirect("~/JobInfo.aspx");
}
in the first page and when i navigate to second page , i want to be able to retrieve PersonId , but thsi message appeares in this line:
(
globalvaribles.PersonId = int.Parse(cmd.ExecuteScalar().ToString());
)
NullRefrence Exception Was Unhandeled by user code.
Object reference not set to an instance of an object
and i don't know whether this way of retreiving PersonId is correct or not?