C#:string username = Session["username"].ToString();
this.lab_welcom.Text = "欢迎光临:" + username;错误提示:用户代码未处理 System.NullReferenceException
  Message="未将对象引用设置到对象的实例。"但跟踪发现 username 不为空,此代码是写在母版页的,如不写在母版页为正常.请问是什么原因?

解决方案 »

  1.   

    if(Session["username"] == null) return;
      

  2.   

    Session["username"] 是不为空的,代码中已经判断过了,没写出来.
    跟踪发现 username 不为空,
      

  3.   

    那你调试,确定哪个为null先啊。
    this.lab_welcom是不是还没创建出来呢?
      

  4.   


    Session["username"]不为空?
    那你跟一下哪里崩掉的~
      

  5.   

    刚测了一下,好像是lab_welcom没有创建,但lab_welcom是母版页窗体上的一个控件,怎么会没有创建呢?
      

  6.   

    你的代码是写在哪个事件里的?写在page_load吗?
      

  7.   


      protected void Page_Load(object sender, EventArgs e)
        {
            if (Session["username"] != null)
            {
                this.lab_welcom.Text = "欢迎光临:";
                string username = Session["username"].ToString();
                this.lab_welcom.Text = "欢迎光临:" + username;
            }
            else
                Response.Redirect("logOut.aspx");
        }在this.lab_welcom.Text = "欢迎光临:"; 那就报错了(未将对象引用设置到对象的实例)为什么是控件还没创建呢?
      

  8.   

    string username;
    if(Session["username"]!=null)
    {
    username= Session["username"].ToString();
    this.lab_welcom.Text = "欢迎光临:" + username;
    }
      

  9.   

    直接引用模板页的内容?http://msdn.microsoft.com/zh-cn/library/xxwa0ff0(VS.80).aspx
      

  10.   

    if(Session["username"]!=null)
    {
     this.lab_welcom.Text = "欢迎光临:" +Session["username"].ToString();
    }
      

  11.   

    你敲this.后,能找到lab_welcom吗?
      

  12.   

    谢谢 wuyazhe的提醒,我把Label放在了可编辑区域,所以执行的时候控件还没创建,也谢谢其它兄弟的提醒