Search   Articles   Dev Forums   Personalize   Favorites   Member Login   ASP.Net Hosting
DevASP.NET for ASP.NET, VB.NET, XML and C# (C-Sharp) Developers Sunday, February 19, 2006

Search Directory
ESET
ASP.NET
VB.Net
C-Sharp
SQL Server
 
More Partners >>

Programmatically adding Control in GridView Cell (Controls.Add)

Author: DevASP Team
Download Source Code : 708_GridViewControl.zip

In this article I will try to explain you how you can add control in gridview cell programmatically.

Often as developer we face scenario like need of new control while running the application or developer wants to display record set in gridview cell by retrieving data from database. In aspx drop a gridview control and label control. The page will be like as follows:

 

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

                <Columns>

                    <asp:TemplateField HeaderText="Controls">

                        <ItemTemplate>

                            <asp:Label ID="lbl" runat="server" Text="DropDownControl" ></asp:Label>

                        </ItemTemplate>

                    </asp:TemplateField>

                </Columns>

            </asp:GridView>

            <asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />

 

On page load bind the gridview control with arraylist. So that gridview will display on your web form.

 

    protected void Page_Load(object sender, EventArgs e)

    {

        ArrayList al = new ArrayList();

        al.Add("item1");

        gv.DataSource = al;

        gv.DataBind();

    }

 

The trick to adding the control to cell is on button click event the code for adding the control is as follows:

 

    protected void Button1_Click(object sender, EventArgs e)

    {

        DropDownList ddl = new DropDownList();

        ddl.Visible = true;

        ddl.ID = "ddl1";

        ddl.Items.Add("Item1");

        TableCell cell = new TableCell();      

        gv.Rows[0].Cells.Add(cell);

        gv.Rows[0].Cells[0].Controls.Add(ddl);

    }

 

In above sample I have simply uses the Controls.Add property which adds the control in cell.






Article Comments
Name:  Rogelio Leyva 
Hi!!! I need some similiar, I need to merge to columns, one column show the year(ex. 2008) and other the month(ex. 1=) I need to join both and present de information like (january 2008)

maybe you can help me

Name:  Thomas 
in gridview where your binding your colums in template field do it like this

DataBinder.Eval(Container.DataItem, "months").ToString() + " " + DataBinder.Eval(Container.DataItem, "years").ToString()

Name:  Anand 
Thank you. This article has really helped me. I was looking for the same thing for my project.

Name:  Susanta 
This article has really helped me. I was looking for the same thing for my project.

Name:  Sagar 
Thank you....It helped me lot



Disclaimer - Privacy
Copyright © 2008 DevASP.net