0

I desperately seeks in vain. I want to bind a List(T) of Users Controls (.ascx) to a gridview. I initialize my controls in code-behind :

List<myControl> ctrls = new List<myControl>();
myControl ctr = LoadControl("~/Control.ascx") as myControl;
ctr.Name = ...
// ...
ctrls.Add(myControl); // add new control to the collection

And after, i bind this list to Gridview control :

this.GridView1.DataSource = ctrls;
this.gridView1.DataBind();

In the Page_Load event with condition If (!IsPostBack). This does not work: the representation of the object is displayed. Whereas when I put the controls in a Panel, all worked.

John Saunders
  • 160,644
  • 26
  • 247
  • 397
Rikimaru
  • 73
  • 6
  • 1
    Why do you want them in a GridView? What purpose would that serve? Why not just put them in a panel? – mason Oct 03 '14 at 17:34
  • for paging by n elements :/ – Rikimaru Oct 03 '14 at 17:39
  • I think you've got an [XY question](http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem) here. – mason Oct 03 '14 at 17:39
  • Build a pager control, or just build a pager into the page. You do not need all the overhead of the GridView. Even if you wanted to use a GridView, you're going about it the wrong way. You wouldn't bind it to the list of controls. You'd bind it to data, and let the templating system create your custom controls for you. And if you don't need multiple columns, you should use a Repeater. – mason Oct 03 '14 at 17:42
  • Tracks for paging with panel ? – Rikimaru Oct 03 '14 at 17:46
  • [ListView](http://msdn.microsoft.com/en-us/library/vstudio/bb398790(v=vs.100).aspx) sounds more appropriate, but make sure you bind to the data (like in my answer) rather than to a list of controls. – mason Oct 03 '14 at 17:53

1 Answers1

0

Don't use a GridView for this. Use a Repeater. And bind it to the data, not to list of controls. Example:

<asp:Repeater runat="server" id="ControlsRepeater">
    <ItemTemplate>
       <uc:MyControl runat="server" />
    </ItemTemplate>
</asp:Repeater>

Code Behind

protected void Page_Load(object sender, EventArgs e)
    {
    if(!IsPostBack)
        {
        var myData=GetData(); //should return some type of ICollection representing your data to bind to
        ControlsRepeater.DataSource=myData;
        ControlsRepeater.DataBind();
        }
    }

If you want paging, then you should take advantage of lazy loading (the Entity Framework handles this for you if you use that) and the Linq functions .Take() and .Skip().

Community
  • 1
  • 1
mason
  • 31,774
  • 10
  • 77
  • 121