将数据动态添加到网格视图中的asp文字控件

huM*_*pty 2 c# asp.net

我正在尝试将数据添加到gridview中的文字中.目前代码看起来像这样

protected void GvListingRowDataBound(object sender, GridViewRowEventArgs e)
{
       var query = DisplayAllData();
       Literal info = (Literal)e.Row.FindControl("ltritemInfo");

       if(query != null)
       {
           foreach (var listing in query)
           {
               var list = DisplayListById(listing.id);
               info.Text = "<h3>" + list.title + "</h3>";
               info.Text += "<h4>" + list.description + "</h4>";
           }
       }
}
Run Code Online (Sandbox Code Playgroud)

这将产生错误

你调用的对象是空的.

如果有人对此有所了解,那将是很有帮助的

谢谢

p.c*_*ell 5

确保您只对数据行进行操作,而不是对页眉,页脚,分隔符,寻呼机等进行操作DataControlRowtype.对此的枚举是.这就是您的info对象/引用为空的原因,因为它首先在标题上操作.

  • 检查是否e.Row.RowType是类型DataRow.
  • 为安全起见,还要检查您info是否为空.
protected void GvListingRowDataBound(object sender, GridViewRowEventArgs e)
{
    if(e.Row.RowType == DataControlRowType.DataRow)
    {        
       var query = DisplayAllData();
       Literal info = (Literal)e.Row.FindControl("ltritemInfo");

       if(query != null && info !=null) 
       {
           foreach (var listing in query)
           {
                var list = DisplayListById(listing.id);
                info.Text = string.Format("<h3>{0}</h3><h4>{1}</h4>",
                               list.title, list.description);    
           }
       }
   }
}
Run Code Online (Sandbox Code Playgroud)