开发者

Adding data dynamically to a asp literal control inside a grid view

开发者 https://www.devze.com 2023-04-02 07:42 出处:网络
I\'m trying to add data to a literal which place inside a gridview. Currently code look like this protected void GvListingRowDataBound(object sender, GridViewRowEventArgs e)

I'm trying to add data to a literal which place inside a gridview. Currently code look like this

protected void GvListingRowDataBound(object sender, GridViewRowEventArgs e)
{
       var query = DisplayAllData();
       Literal info = (Literal)e.Row.FindControl("ltritemInfo");开发者_如何学Go

       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. This is why your info object/reference is null, as it operates on the header first.

  • Check that the e.Row.RowType is of type DataRow.
  • For safety, also check that your info is not 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);    
           }
       }
   }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号