日期:2014-05-18  浏览次数:20764 次

出现未将对象引用设置到对象的实例错误?
我想先把用户信息先绑定,再进行修改,可总出现出现未将对象引用设置到对象的实例错误,大家帮忙看一下这是什么意思
protected void Page_Load(object sender, EventArgs e)
  { 
   
  if (!IsPostBack)
  {
  string str=Convert.ToString (Session["UserName"]);

  DataTable dt = user.GetInformationByName(str);
   
  this.lblpno.Text = dt.Rows[0][0].ToString();

  this.lbltruename.Text = dt.Rows[0][1].ToString();

  this.lblsex.Text = dt.Rows[0][2].ToString();
  this.lbldepartment.Text = dt.Rows[0][3].ToString();

  this.lblclassno.Text = dt.Rows[0][4].ToString();
  this.txtemail.Text = dt.Rows[0][5].ToString();

  this.lblrole1.Text = dt.Rows[0][6].ToString();
   
  }}
   
其中函数GetInformationByName()是这样子的:
  public static DataTable GetInformationByName(string UserName)
  {
  SqlConnection myConnection = new SqlConnection(ConfigurationSettings.AppSettings["ConnectionString"]);
  string strQuery = "selcet Pno,TrueName,sex,Department,ClassNo,Email,role1 from Users where UserName=" + UserName ;

  try
  {
  SqlDataAdapter myDA = new SqlDataAdapter(strQuery, myConnection);
  DataSet myDS = new DataSet();
  myDA.Fill(myDS, "Users");
  return myDS.Tables["Users"];
  }
  catch (Exception ex)
  {

  return null;
  }
  }
   
   
   
  运行后总出现上述错误,我感觉代码没错呀,就是不知道哪的问题? 
 

------解决方案--------------------
C# code

protected void Page_Load(object sender, EventArgs e) 
    {  
        
          if (!IsPostBack) 
          { 
          string str=Convert.ToString (Session["UserName"]); 

          DataTable dt = user.GetInformationByName(str); 
          if(dt!=null)//如果不为空则设置
{
              this.lblpno.Text = dt.Rows[0][0].ToString(); 

              this.lbltruename.Text = dt.Rows[0][1].ToString(); 

              this.lblsex.Text = dt.Rows[0][2].ToString(); 
              this.lbldepartment.Text = dt.Rows[0][3].ToString(); 

              this.lblclassno.Text = dt.Rows[0][4].ToString(); 
              this.txtemail.Text = dt.Rows[0][5].ToString(); 

              this.lblrole1.Text = dt.Rows[0][6].ToString(); 
          }
          }
}

------解决方案--------------------
C# code

          if (!IsPostBack) 
          { 
              if(Session["UserName"] != null)
                  string str=Convert.ToString (Session["UserName"]); 

              DataTable dt = user.GetInformationByName(str); 
          
              if(dt != null || dt.Rows.Count > 0)
              {
                  this.lblpno.Text = (dt.Rows[0][0]!=null?dt.Rows[0][0].ToString():""); 

                  this.lbltruename.Text = dt.Rows[0][1]!=null?dt.Rows[0][1].ToString():"");

                this.lblsex.Text = dt.Rows[0][2]!=null?dt.Rows[0][2].ToString():"");           this.lbldepartment.Text = dt.Rows[0][3]!=null?dt.Rows[0][3].ToString():"");

                  this.lblclassno.Text = dt.Rows[0][4]!=null?dt.Rows[0][4].ToString():"");
                  this.txtemail.Text = dt.Rows[0][5]!=null?dt.Ro