简体   繁体   English

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

[英]Adding data dynamically to a asp literal control inside a grid view

I'm trying to add data to a literal which place inside a gridview. 我试图将数据添加到放置在gridview内的文字。 Currently code look like this 当前代码如下所示

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

This will generate an error 这将产生一个错误

Object reference not set to an instance of an object. 你调用的对象是空的。

If anyone has an idea about this it will be great help 如果有人对此有想法,那将是很大的帮助

Thanks 谢谢

Ensure you're only operating on the data rows, and not the header, footer, separator, pager, etc. The enum for this is DataControlRowtype . 确保仅对数据行进行操作,而不对页眉,页脚,分隔符,分页器等进行操作。其枚举是DataControlRowtype This is why your info object/reference is null, as it operates on the header first. 这就是为什么您的info对象/引用为null的原因,因为它首先对标头进行操作。

  • Check that the e.Row.RowType is of type DataRow . 检查e.Row.RowType是否为DataRow类型。
  • For safety, also check that your info is not null. 为了安全起见,还请检查您的info是否不为null。
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);    
           }
       }
   }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM