Sana.91 Sana.91 - 1 month ago 7
ASP.NET (C#) Question

Unable to cast Session variable Containing a List Of object to list

Why Is the following code producing error of "Object reference not set to an instance of an object Even when i am using the set session method inboth of the button click events?

public partial class MergePopUp : System.Web.UI.Page
{

List<MergeAccounts> Mlist = new List<MergeAccounts>();

protected void Page_Load(object sender, EventArgs e)
{

}
private void SetSession()
{
if (Session["Account"] == null)
{
Session["Account"] = Mlist;
}
}


protected void AddToMergeList_Click(object sender, EventArgs e)
{
MergeAccounts obj = new MergeAccounts();
obj.AccountNumber = Convert.ToInt32(AccountNumber.Text);
obj.PinNumber = Convert.ToInt32(PinNumber.Text);
int temp = obj.IsAccNoValid(obj.AccountNumber, obj.PinNumber);
if (temp == 0)
{
FoundOrNot.Visible = true;
FoundOrNot.Text = "Enter a valid Pin Number against this Account number";
}
else
{
DataSet MyDataSet = obj.ShowDetails(obj.AccountNumber, obj.PinNumber);
foreach (DataRow myRow in MyDataSet.Tables[0].Rows)
{
AccountTitle.Text = myRow["Title"].ToString();
Balance.Text = myRow["Balance"].ToString();
CreationDate.Text = myRow["CreationDate"].ToString();
}
obj.AccountTitle = AccountTitle.Text;
obj.Balance = Convert.ToDouble(Balance.Text);
obj.CreationDate = Convert.ToDateTime(CreationDate.Text);
Mlist.Add(obj);
Session["Account"] = Mlist;
SetSession();
}
}
protected void AddNext_Click(object sender, EventArgs e)
{
foreach (TextBox i in this.Page.Form.Controls.OfType<TextBox>().ToList())
{
i.Text = null;
}
FoundOrNot.Visible = false;
}
protected void CheckList_Click(object sender, EventArgs e)
{
SetSession();
Response.Redirect("Merge.spx");
}

}

Answer

are the two buttons on the same page? If so, create a method accessible to both buttons where the session variable is set. Make sure you check if it's already set so that it's only set once.

private void SetSession()
{
   if(Session["Account"] == null)
      Session["Account"] = "Value";
   else
      //what do you want to do here
}


protected void button1_click(.....)
{
    SetSession();
    //do something
}

protected void button2_click(....)
{
    SetSession();
    //redirect
}

by this your session is always set whether first button or second button is clicked