V.J.
V.J.

Reputation: 928

Create Gridview totally programatically in asp.net c# 4.0

I want to create more than one gridview. And i want to add them from code behind(.cs) file. Here is my code which is almost worked. But can anyone find whats an issue with this?

sample.aspx:

    <body>
    <form id="form1" runat="server">
           <%CreateGridView();%>
    </form>
    </body>

Sample.aspx.cs:

    using System;
    using System.Collections;
    using System.Web.UI;
    using System.Web.UI.WebControls;

    public partial class _Default : System.Web.UI.Page
    {
    protected void Page_Load(object sender, EventArgs e)
    {
    }

    protected GridView CreateGridView()
    {
    GridView gv = new GridView();
    gv.ID = "_gridview1";
    Queue q = new Queue();
    for (int i = 0; i < 20; i++)
        q.Enqueue(i);
    gv.DataSource = q;
    gv.DataBind();
    gv.Visible = true;
    return gv;
    }
    }

Upvotes: 2

Views: 12164

Answers (2)

David
David

Reputation: 73564

But can anyone find whats an issue with this?

  • If the GridView will be editable, you'll lose your user's changes on each postback. (Usability/functionality break)
  • It won't persist to the Viewstate and the grids will need to be rebuilt on every page postback. (Performance issue)

A safer approach may be to add an asp:Panel (sat you call it GridViewPlaceHolderPanel) to the page, and in the Page_Init event, build your GridView in code behind and add it using

GridViewPlaceHolderPanel.Controls.Add(gv);

However, if the two issues I listed aren't concerns (It won't be editable and you want it to be built on every postback) then your approach should work fine.

Upvotes: 2

JP Hellemons
JP Hellemons

Reputation: 6047

Sample.aspx:

<body>
    <form id="form1" runat="server">
        <asp:PlaceHolder id="ph" runat="server"/>
    </form>
</body>

Sample.aspx.cs:

protected void Page_Load(object sender, EventArgs e)
{
    for (int i = 0; i < 20; i++)
    {
        GridView gv = new GridView();
        gv.ID = "_gridview" + i;
        Queue q = new Queue();
        q.Enqueue(i);
        gv.DataSource = q;
        gv.DataBind();
        ph.Controls.Add(gv);
    }
}

Upvotes: 6

Related Questions