C# – Create multiple gridviews in code behind

asp.netcgridviewvisual-studio-2008

This is very interesting..

I want to have multiple gridviews in a panel. and the number of gridviews is not fixed..

So basically i think there should be no code in the .aspx page as i have to create the gridview in codebehind.

I have the code for 1 gridview in one panel.. where i define the grid view in the HTML page and populate it from the code behind.

Here is the code for that.. can any 1 please help me with the multiple gridviews…

this is on the .aspx page

       <asp:GridView ID="GridView1" runat="server"  AutoGenerateColumns="False" 
      AllowSorting="True" CellSpacing="2" onsorting="GridView1_Sorting"
                    Width="100%" ForeColor="White" GridLines="None" 
                      ondatabound="GridView1_DataBound1">

       <Columns>
                            <EditItemTemplate>
                                <asp:Label ID="Label1" runat="server" Text='<%# Eval("PolicyID") %>'></asp:Label>
                            </EditItemTemplate>
                            <ItemTemplate>
                                <asp:Label ID="Label1" runat="server" Text='<%# Bind("PolicyID") %>'></asp:Label>
                            </ItemTemplate>
                        </asp:TemplateField>
      </Columns>
    </asp:GridView>

this is the code behind

 protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            DataTable dt = new DataTable();
            SqlConnection connection = new SqlConnection(Session["ConnectionStringSQL"].ToString()); 
            connection.Open();
            SqlCommand sqlCmd = new SqlCommand("SELECT Policies.PolicyID, FROM Policies", connection);
            SqlDataAdapter sqlDa = new SqlDataAdapter(sqlCmd);

            sqlDa.Fill(dt);
            connection.Close();

            if (dt.Rows.Count > 0)
            {
                for (int j = 0; j < dt.Rows.Count; j++)
                {
                    policyID.Add(dt.Rows[j]["PolicyID"].ToString());

                }
                taskTable.Columns.Add("PolicyID");


                if (policyID.Count != 0)
                {
                    for (int k = 0; k < policyID.Count; k++)
                    {
                        DataRow tableRow = taskTable.NewRow();

                        tableRow["PolicyID"] = policyID[k];

                        taskTable.Rows.Add(tableRow);
                    }

                    Session["TaskTable"] = taskTable;

                    GridView1.DataSource = Session["TaskTable"];
                    GridView1.DataBind();
                }
            }
        }
    }

Best Answer

Not tested, but this kind of thing should do it:

for (int i=0;i<5;i++) {
   GridView gv = new GridView();
   gv.DataSource = datasources[i];
   Page.Controls.Add(gv);
}
Page.DataBind();