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

GridView中显示Panel(项目收尾中,急!)
博客文章中设一个密码保护功能,设置完,文章受保护则填入密码Password,如果不受保护,则设密码Password为空NULL,在访问别人博客时,在文章列表GridView中放置两个Panel,一个是有密码显示的内容,一个是没有密码显示的输入密码Panel,这时我需要怎样判断来显示这两个Panel,我的做法,如下:
 protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
  {
  string cmdPass = string.Format("select Password from Articles where BlogID='{0}'AND Status='{1}'", Session["Blogid"], 0);
  DataTable dt1 = new DataTable();
  DataSet ds1 = new DataSet();
  ds1 = DAAB.ExecuteDataset(SqlDB.GetConnection(), CommandType.Text, cmdPass);
  dt1 = ds1.Tables[0];
  string pass = dt1.DefaultView[0]["Password"].ToString();
  Panel p1 = (Panel)e.Row.FindControl("pPassNone");
  Panel p2 = (Panel)e.Row.FindControl("pPass");
  if (pass == null)
  {
  p1.Visible = true;
  p2.Visible = false;
  }
  else
  {
  p1.Visible = false;
  p2.Visible = true;
  }
  }
可是提示我“未将对象引用设置到对象实例”这样的错误

------解决方案--------------------
你先把aspx页面中panel的visiable属性都设为true,不要设置为false.
这样试试看,visiable为false找不到这个control,估计
------解决方案--------------------
string pass = dt1.DefaultView[0]["Password"].ToString(); 
先看一下dt1.DefaultView[0]["Password"]是否为空,如果为空ToString()肯定会报错了,问题应该不是出现在Panel 

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

        Panel p1 = (Panel)e.Row.FindControl("pPassNone"); 
        Panel p2 = (Panel)e.Row.FindControl("pPass"); 
if(p1!=null || p2!=null)
{
        if (pass == null) 
        { 
            p1.Visible = true; 
            p2.Visible = false; 
        } 
        else 
        { 
            p1.Visible = false; 
            p2.Visible = true; 
        } 
}