Wednesday, September 23, 2015

Loading controls dynamically in ASP.NET

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);
    }
}


If you are searching life partner. your searching end with kpmarriage.com. now kpmarriage.com offer free matrimonial website which offer free message, free chat, free view contact information. so register here : kpmarriage.com- Free matrimonial website

0 comments:

Post a Comment