dynamically filled DropDownList does not retain value on postback

dynamically filled DropDownList does not retain value on postback

I have a form which is made to "Create a new profile". My problem is about DropDownLists.

The first DropDown dynamically populate the second one in function of its value.

see this picture:

http://image.noelshack.com/fichiers/2013/22/1369819471-picture-help.png

And the following picture:

http://image.noelshack.com/fichiers/2013/22/1369830738-help2.png

You can see that my 2nd ddl ("Fonction") is correctly filled BUT when I click on the submit button, the value becomes the null value ("Sélectionnez...") and so my RequiredFieldValidator makes the page not valid!

It seems like my 2nd DropDownList is bounded on every postback even if it's not because of SelectedIndexChanged of my 1st DropDownList. The SelectedIndexChanged of the 1st DropDownList is always called on postback and so it throws "populateDdl()" at every PostBack (if a value is selected).

When I click on submit button, it registers a blank value in my database.

What am I missing?

Aspx code:

<asp:DropDownList ID="ddlTypePN" runat="server" DataSourceID="SqlTypePN" EnableViewState="true" 
        DataTextField="libelle" DataValueField="valeur" AutoPostBack="true" OnSelectedIndexChanged="ddlTypePN_SelectedIndexChanged" 
        OnDataBound="ddlTypePN_DataBound" > </asp:DropDownList> 

<asp:DropDownList runat="server" ID="ddlFctPN" AppendDataBoundItems="false" OnDataBound="ddlFctPN_DataBound" > </asp:DropDownList> 

Code behind:

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        ddlTypeProf.DataBind(); // don't care
        ddlSsoSrc.DataBind(); // don't care
        ddlTypePN.DataBind(); // The ddl that populate my 2nd ddl
    }
}

protected void ddlTypePN_SelectedIndexChanged(object sender, EventArgs e)
{
    string type = ddlTypePN.SelectedValue.ToString().Trim();
    // if PNT
    if (type.ToUpper().Trim().Equals("PNT"))
    {               
        ddlFctPN.Enabled = true;
        ddlTypeAv.Enabled = true;
        rfvTypeAv.Enabled = true;
        populateDdl();

    }
    else if (type.ToUpper().Trim().Equals("PNC"))
    {                
        ddlFctPN.Enabled = true;
        ddlTypeAv.Enabled = false;
        rfvTypeAv.Enabled = false;
        populateDdl();
    }     
}

void populateDdl()
{
    string val = "fct"+ddlTypePN.SelectedValue.ToString().Trim(); // Used for SELECT
    SqlConnection sqlConn = new SqlConnection(ConfigurationManager.ConnectionStrings["My_DB"].ConnectionString);
    ddlFctPN.Items.Clear();
    DataTable subjects = new DataTable();
    try
    {
        SqlDataAdapter adapter = new SqlDataAdapter("My SELECT", sqlConn);
        adapter.Fill(subjects);

        ddlFctPN.DataSource = subjects;
        ddlFctPN.DataTextField = "libelle";
        ddlFctPN.DataValueField = "valeur";
        ddlFctPN.DataBind();
    }
    catch (Exception ex)
    {
        lblErr.Text = ex.Message;
    }
    ddlFctPN.Items.Insert(0, new ListItem("Sélectionnez...", "null"));
}

Solution moved to an answer from the question:

I finally found what the problem was. Every control was in an <asp:Table>, and I had to set EnableViewState="true" on this table in order to be able to keep the value after postback.

retaining value of dynamic dropdownlist on postback, You have to check whether postback event is fired or not. I put some code below. Hide Copy Code. protected override void OnInit(EventArgs e)  It seems like my 2nd DropDown is bounded on every postback even if it's not because of SelectedIndexChanged of my 1st DropDown.. The SelectedIndexChanged the 1st DropDown is always called on postback and so it throws "populateDdl()" at every PostBack (if a value is selected). When I click on submit button, it register a blank value in my database.


if(!IsPostBack)

 {

  populateDdl();

 }

Maintain The State Of Dynamic Added User Control On Each PostBack, Get TextBox , Dropdown, CheckBox control Values In Aspx.cs Page From User But when you are with dynamic controls the will not able to maintain its all of your filled data lost from all textboxes and other controls on form. Whenever i change the value from default to something else in dropdownlistit comes back to the original value(and not the selected one).i tried to write the code on Page Init as well but then it does not shows the value at all in dropdownbox after postback.Please help..


put this code under this condition

if(!Page.IsPostBack)
            {

       // Your Code Here

            }

Dynamic Controls in Placeholder lossed after postback, but when Postback happen There is nothing in Placeholder Control it is simply blank. How i can get option selected by users in dropdown list's which in contined to hold "Comments".. upon postback, all my comments are suddenly Add(lblTitle); // Create one logical set of controls do not assign values! Controls inside the dynamically added web user control does not retain there value on post back caused by the dropdown list 0 asp.net saving control values on postback


you are population DD1 in every post back

to avoid this use

if(!IsPostBack)    
 {
   populateDdl();
 }

Retaining values of a dynamically created dropdownlist across , The issue i am having is after the controls are created and binded, if. the dropdownlist but the event is not fired though the autopostback is set  The list items in a DropDownList are not stored in view state. You'll have to add them on every postback. What's stored in view state is the selected index - ie. the 'value' of the control. Edit: Well, it seems I learned something today.


From your mark up you haven't set the AutoPostBack property on the second drop down. So it shouldn't fire a post back when the second drop down index has changed (unless you are programmatically causing a post back).

I've copied your code into my solution, it seems to be behaving...

<asp:Label ID="lblErr" runat="server"></asp:Label>
<asp:DropDownList ID="ddlTypePN" runat="server" EnableViewState="true"
    AutoPostBack="true" OnSelectedIndexChanged="ddlTypePN_SelectedIndexChanged"
    OnDataBound="ddlTypePN_DataBound">
</asp:DropDownList>

<asp:DropDownList runat="server" ID="ddlFctPN" AppendDataBoundItems="false" OnDataBound="ddlFctPN_DataBound">
</asp:DropDownList>

And the code...

protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                ListItemCollection items = new ListItemCollection();
                items.Add(new ListItem("PNT", "PNT"));
                items.Add(new ListItem("PNC", "PNC"));

                ddlTypePN.DataSource = items;
                ddlFctPN.DataBind();
                ddlTypePN.DataBind(); // The ddl that populate my 2nd ddl

                ddlTypePN.Items.Insert(0, new ListItem("Sélectionnez...", "null"));
            }
        }

        protected void ddlTypePN_SelectedIndexChanged(object sender, EventArgs e)
        {
            string type = ddlTypePN.SelectedValue.ToString().Trim();

            // if PNT
            if (type.ToUpper().Trim().Equals("PNT"))
            {
                ddlFctPN.Enabled = true;
                populateDdl();

            }
            else if (type.ToUpper().Trim().Equals("PNC"))
            {
                ddlFctPN.Enabled = true;
                populateDdl();
            }        
        }

        protected void ddlTypePN_DataBound(object sender, EventArgs e)
        {

        }

        protected void ddlFctPN_DataBound(object sender, EventArgs e)
        {

        }

        void populateDdl()
        {

            ddlFctPN.Items.Clear();
            lblErr.Visible = false;

            try
            {
                ListItemCollection items = new ListItemCollection();
                items.Add(new ListItem("One", "1"));
                items.Add(new ListItem("Two", "2"));
                items.Add(new ListItem("Three", "3"));

                ddlFctPN.DataSource = items;
                ddlFctPN.DataBind();
            }
            catch (Exception ex)
            {
                lblErr.Text = ex.Message;
                lblErr.Visible = true;
            }


            ddlFctPN.Items.Insert(0, new ListItem("Sélectionnez...", "null"));

        }

    }

[PDF] TRULY Understanding ViewState Table of , dynamically filled DropDownList does not retain value on postback. I have a form which is made to "Create a new profile". My problem is about DropDownLists. This happens because the code to populate the DropDownList is not placed inside the Not IsPostBack condition and hence the DropDownList is populated twice i.e. when the page loads first time as well as when the Button is clicked, which clears its ViewState and ultimately the Selected Item Value.


SelectedValue lost on postback in dynamically added user controls , DropDownList within Dynamically-Loaded User Control: Contents not Restored Populating a Control according to User-selected value of a previous control .. 32 does not keep its state on postback, even though viewing the page trace, the viewstate for that I have a dropdownlist which i am getting filled using AJAX​. Here Mudassar Ahmed Khan has explained how to use ViewState with dynamic controls i.e. Retain / maintain / preserve State (values) of dynamically created controls on PostBack in ASP.Net. Dynamically created controls are lost on PostBack and hence we need to recreate the dynamic controls in the PreInit event of the page.


Populating a DropDownList using AJAX and ASP.NET: ASP Alliance, This works with asp:DropDownList and with telerik:radComboBox from 2010 Q2. As I said below, the selected value is not overridden in the Telerik DLL you might be filling different data and therefore it is not valid to keep  Here Mudassar Ahmed Khan has explained how to solve the problem of dynamic control disappearing after PostBack in ASP.Net i.e. Persists dynamic controls after PostBack in ASP.Net using C# and VB.Net. Dynamically created controls have to be recreated on PostBack in order to persist dynamic controls across PostBacks.


DropDownList Class (System.Web.UI.WebControls), A change in the selected value of the first drop-down list should populate the second the XmlHttp variable will be set to null and the AJAX code will not be executed. spell is nice and make me fill alive again i will keep sharing you good work all Hi sir,when i's using dropdown with autopostback property in ASP.net(c#),i  1 Dynamic panel pnlDropDownList and added it to the form control on the page. 2. Dynamic LinkButton btnAddDdl attached a Click event btnAdd_Click to it and added to the form control. 3. A function called RecreateControls is being called which I’ll explain later in the article . On the Click event of the dynamic LinkButton I have added the