Reputation: 928
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
Reputation: 73564
But can anyone find whats an issue with this?
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
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