Homepage image
Sample of the Day RSS Feed

Sample Downloads: http://code.msdn.microsoft.com/AddDynamicallyControlstoGri-d74fe84f 

Today’s sample demonstrates how to add dynamically created controls to the GridView in the CodeBehind page. For some people, when the refresh or the page is PostBack, the dynamically created controls will disappear from GridView, this sample will show how to resolve this issue.

The sample was written by our star sample writer: Arwind Gao.

imageYou can find more code samples that demonstrate the most typical programming scenarios by using Microsoft All-In-One Code Framework Sample Browser or Sample Browser Visual Studio extension. They give you the flexibility to search samples, download samples on demand, manage the downloaded samples in a centralized place, and automatically be notified about sample updates. If it is the first time that you hear about Microsoft All-In-One Code Framework, please watch the introduction video on Microsoft Showcase, or read the introduction on our homepage http://1code.codeplex.com/.

 

Introduction

The sample code demonstrates how to add dynamically created controls to the GridView in the CodeBehind page. For some people, when the refresh or the page is PostBack, the dynamically created controls will disappear from GridView, this sample will show how to resolve this issue.

 

Running the Sample

Please follow these demonstration steps below.

Step 1: Open the CSASPNETAddDynamicControltoGridView.sln. Expand the CSASPNETAddDynamicControltoGridView web application and press Ctrl + F5 to show the Default.aspx.

Step 2: We will see a web page like below:

image

Step 3:  Click on a LinkButton to do a PostBack operations, the page will like show below:

image

 

Using the Code

Step 1. Create a C# "ASP.NET Web Application" in Visual Studio 2010/Visual Web Developer 2010. Name it as “CSASPNETAddDynamicControltoGridView".

Step 2.  Add a GridView Control to “Default.aspx” page then rename it to "gdvCustomer". This page will bind the data and show the dynamically created LinkButton Control. In order to realize this page:

First, we need to bind data to gdvCustomer.

<asp:GridView ID="gdvCustomer" runat="server" AutoGenerateColumns="False" OnDataBound="gdvCustomer_DataBound" 
           DataKeyNames="Id" DataSourceID="SqlDataSource1"> 
           <Columns> 
               <asp:TemplateField> 
                   <ItemTemplate> 
                   </ItemTemplate> 
               </asp:TemplateField> 
               <asp:BoundField DataField="Id" HeaderText="Id" InsertVisible="False" ReadOnly="True" 
                   SortExpression="Id" /> 
               <asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name" /> 
               <asp:BoundField DataField="Age" HeaderText="Age" SortExpression="Age" />               
           </Columns> 
       </asp:GridView> 
       <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString %>" 
           SelectCommand="SELECT [Id], [Name], [Age] FROM [CustomerInfo]"></asp:SqlDataSource> 

Then, we need to call DataBound method to add dynamically created Control.

        protected void gdvCustomer_DataBound(object sender, EventArgs e) 
        { 
            AddLinkButton(); 
        } 
 
 
        /// <summary> 
        /// Add a LinkButton To GridView Row. 
        /// </summary> 
        private void AddLinkButton() 
        { 
            foreach (GridViewRow row in gdvCustomer.Rows) 
            { 
                if (row.RowType == DataControlRowType.DataRow) 
                { 
                    LinkButton lb = new LinkButton(); 
                    lb.Text = "Approve"; 
                    lb.CommandName = "ApproveVacation"; 
                    lb.Command += LinkButton_Command; 
                    row.Cells[0].Controls.Add(lb); 
                } 
            } 
        } 

To test the LinkButton, we add an event for the LinkButton .

protected void LinkButton_Command(object sender, CommandEventArgs e) 
        { 
            if (e.CommandName == "ApproveVacation") 
            { 
                //This is to test 
                LinkButton lb = (LinkButton)sender; 
                lb.Text = "OK"; 
            } 
        } 

[Note]Finally, add LinkButton in the Page_Init event and override the OnInit method.

protected void Page_Init(object sender, EventArgs e) 
       { 
           gdvCustomer.DataBind(); 
       } 
 
 
       protected void Page_Load(object sender, EventArgs e) 
       { 
           if (!IsPostBack) 
           { 
               AddLinkButton(); 
           } 
       } 
 
 
       /// <summary> 
       /// To initialize the page. 
       /// </summary> 
       /// <param name="e"></param> 
       protected override void OnInit(EventArgs e) 
       { 
           base.OnInit(e); 
       } 

 

More Information

 ASP.NET Page Life Cycle Overview