无法转换Session变量包含要列出的List Of List

时间:2012-05-30 12:40:53

标签: asp.net session c#-4.0 session-variables

为什么以下代码产生错误“对象引用未设置为对象实例即使我在按钮单击事件中使用set session方法?

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");
}

}

3 个答案:

答案 0 :(得分:1)

会话[“帐户”]可能为空。

答案 1 :(得分:0)

在这里设一个断点

Mlit = (List<MergeAccounts>)Session["Account"];

然后按F5逐步执行您的应用程序并将鼠标放在Session [“Account”]上以检查该值 - 它可能为null

答案 2 :(得分:0)

是同一页面上的两个按钮吗?如果是这样,请创建一个可供设置会话变量的按钮访问的方法。确保检查它是否已经设置,以便仅设置一次。

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
}

通过此会话始终设置是否单击第一个按钮或第二个按钮