Support us .Net Basics C# SQL ASP.NET ADO.NET MVC Slides C# Programs Subscribe Buy DVD

Loading controls dynamically in ASP.NET - Part 110

Suggested Videos
Part 107 - Consuming user control custom events
Part 108 - Events and delegates in c#
Part 109 - Loading user controls dynamically

In this video we will discuss about
1. Adding controls dynamically
2. Tips and tricks to maintain the state of dynamically added controls across postback



To maintain the state of controls across postback
1. Add the controls in the page load event, and set their visibility to false.
2. Based on the DropDownList selection, show/hide the dynamically added controls

ASPX Page HTML
<div>
    <asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True">
        <asp:ListItem Text="Please Select" Value="-1"></asp:ListItem>
        <asp:ListItem Text="Select City" Value="DDL"></asp:ListItem>
        <asp:ListItem Text="Enter Post Code" Value="TB"></asp:ListItem>
    </asp:DropDownList>
    <br />
    <asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>
    <br />
    <asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />
</div>



Code Behind Code
protected void Page_Load(object sender, EventArgs e)
{
    TextBox TB = new TextBox();
    TB.ID = "TB1";
    PlaceHolder1.Controls.Add(TB);
    TB.Visible = false;

    DropDownList DDL = new DropDownList();
    DDL.ID = "DDL1";
    DDL.Items.Add("New York");
    DDL.Items.Add("New Jersey");
    DDL.Items.Add("Washington DC");
    PlaceHolder1.Controls.Add(DDL);
    DDL.Visible = false;

    if (DropDownList1.SelectedValue == "TB")
    {
        TB.Visible = true;
    }
    else if (DropDownList1.SelectedValue == "DDL")
    {
        DDL.Visible = true;
    }
}

protected void Button1_Click(object sender, EventArgs e)
{
    if (DropDownList1.SelectedValue == "TB")
    {
        Response.Write(((TextBox)PlaceHolder1.FindControl("TB1")).Text);
    }
    else if (DropDownList1.SelectedValue == "DDL")
    {
        Response.Write(((DropDownList)PlaceHolder1.FindControl("DDL1")).SelectedItem.Text);
    }
}

1 comment:

  1. Dear Venkat please post some sample of how to maintain state of a FileUpload control across post back.

    I have a FileUpload control and a DropDownList with AutoPostBack="True".

    During the SelectIndexChanged event of the DropDownList I am not able to retain the file information the user has chosen.

    Thanks in advance..

    ReplyDelete

If you like this website, please share with your friends on facebook and Google+ and recommend us on google using the g+1 button on the top right hand corner.