Jenny54321
Jenny54321

Reputation: 57

Creating Dynamic number of GridViews

I need a bunch of GridViews to display on my page. I have a List of Lists of Section Objects called dataList, and each List in dataList should be bound to one of the GridViews.

I have this

List<List<Section>> dataList;
foreach (List<Section> sectionList in dataList)
{
    GridView gv = new GridView();
    gv.DataSource = sectionList
    gv.DataBind();
}

and my markup:

 <asp:GridView runat="server" ID="gv" AutoGenerateColumns="true"/>

but when I load the page I can't see anything. How do I display all of the GridViews I created? Does the foreach loop I have successfully bind each GridView to the Lists of dataList? Thanks

Upvotes: 2

Views: 3632

Answers (1)

rs.
rs.

Reputation: 27427

Remove your Gridview markup and Use PlaceHolder control to add dynamic Gridviews, Try this:

<asp:PlaceHolder ID="PlaceHolder1" runat="server"/>

in C#

int i = 1;
foreach (List<Section> sectionList in dataList)
{
    GridView gv = new GridView();
    //generate dynamic id        
    gv.Id = "gv" + i; i++;
    gv.AutoGenerateColumns="true";
    gv.DataSource = sectionList
    gv.DataBind();
    PlaceHolder1.Controls.Add(gv);
}

Upvotes: 2

Related Questions