c# ASP.Net Dynamically populated DropDownList loses selected index on submit button

13,325

Solution 1

When I had trouble with ViewState (that is what l suspect in your case) l used this to restore data to a dynamically populated dropdown object

    public void Page_Load(object sender, EventArgs e){
            if (!IsPostBack)
            {
                Databind();
            }
            else {
                LoadAllViewStates();
            }
    }
    private void Databind()
        {
            DataTable questionnaireDT = null;
            DataTable questionsDT = null;
            DataTable indicatorDT = null;

            DataView tempView = QuestionnaireDS.Select(DataSourceSelectArguments.Empty) as DataView;
            questionnaireDT = tempView.Table;
            ViewState["QuestionnaireDL"] = questionnaireDT;
            QuestionnaireDL.DataSource = ViewState["QuestionnaireDL"];
            QuestionnaireDL.DataBind();

            tempView = QuestionDS.Select(DataSourceSelectArguments.Empty) as DataView;
            questionsDT = tempView.Table;
            ViewState["QuestionList"] = questionsDT;
            QuestionList.DataSource = ViewState["QuestionList"];
            QuestionList.DataBind();

            tempView = IndicatorDS.Select(DataSourceSelectArguments.Empty) as DataView;
            indicatorDT = tempView.Table;
            ViewState["IndicatorLst"] = indicatorDT;
            IndicatorLst.DataSource = ViewState["IndicatorLst"];
            IndicatorLst.DataBind();
        }

        private void LoadAllViewStates()
        {
            QuestionnaireDL.DataSource = ViewState["QuestionnaireDL"];
            QuestionnaireDL.DataBind();

            QuestionList.DataSource = ViewState["QuestionList"];
            QuestionList.DataBind();

            IndicatorLst.DataSource = ViewState["IndicatorLst"];
            IndicatorLst.DataBind();
        }

To restore the selected index, I passed the selectedIndex into a hidden field.

Hope this helps?

By the way, why pass in the DropDownList object as a parameter? Instead call a parameterless function and populate the DropDownList object within the function.

Also, ensure that ViewState isnt switched off.

Solution 2

This should work for you. However, I am sort of confused why you are passing the dropdown to the function to get the states. Do you have multiple dropdowns to be filled? I think we need to see your html to be of more help.

protected void Page_Load(object sender, EventArgs e)
{
    if(!IsPostBack)
        GetStatesForDdl(ddl);
}

 private void GetStatesForDdl(DropDownList ddlStateList)
 {
     AppInputFormProcessor getStates = new AppInputFormProcessor();
     ArrayList States = new ArrayList();
     States = getStates.GetStates();
     ddlStateList.DataSource = States;
     ddlStateList.DataBind();
 }

Solution 3

In your example, you are trying to get the selected value from a session variable, but there's no code shown that actually sets anything in the session.

Even if you have some sort of async call that sets a session variable, this is a very dangerous practice: as soon as someone opens up a 2nd tab, you risk the chance of data corruption.

Share:
13,325
Susan
Author by

Susan

Newbie ASP.Net developer having just received a 2-year degree from a technical college. Attempting to build commercial application using: ASP.Net 4.0, C#, membership provider, SQL, Linq to Entities. I am about 3/4 complete.

Updated on July 30, 2022

Comments

  • Susan
    Susan over 1 year

    I dynamically populate a dropdownlist of all 50 states from an ArrayList on PageLoad. When the user selects the SUBMIT button (btnSubmit_Click event), the SelectedIndex property of the dropdownlist control is always 0 despite what selection the user selects.


    Added more code to help troubleshooting. Getting a -1 both from the session variable (bbb) and from the ddlState.selectedindex (bbb).

    HTML code in form:

    <asp:DropDownList ID="ddlState" runat="server" AutoPostBack="True" 
        onselectedindexchanged="ddlState_SelectedIndexChanged" >
    </asp:DropDownList>
    

    Code Behind:

    protected void Page_Load(object sender, EventArgs e)
    {
        //------------------------------------------------
        // Populates state dropdownlists
        //------------------------------------------------
        if (!IsPostBack)
        {
            GetAllStatesForDdl(ddlDLState);
            GetAllStatesForDdl(ddlOldState);
            GetStatesForDdl(ddlState);
        }
    }
    
    private void GetAllStatesForDdl(DropDownList ddlStateList)
    {
        AppInputFormProcessor getStates = new AppInputFormProcessor();
        ArrayList States = new ArrayList();
        States = getStates.GetAllStates();
        ddlStateList.DataSource = States;
        ddlStateList.DataBind();
    }
    
    private void GetStatesForDdl(DropDownList ddlStateList)
    {
        AppInputFormProcessor getStates = new AppInputFormProcessor();
        ArrayList States = new ArrayList();
        States = getStates.GetStates();
        ddlStateList.DataSource = States;
        ddlStateList.DataBind();
    }
    
    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        int aaa = ddlState.SelectedIndex;
        int bbb = Convert.ToInt32(Session["ddlState"]);
    }
    
    protected void ddlState_SelectedIndexChanged(object sender, EventArgs e)
    {
        Session["ddlState"] = ddlState.SelectedIndex;
    }
    
  • Susan
    Susan about 12 years
    Yes, I have 3 state dropdownlists that need to be populated and there is logic for each predicated on earlier user selections changing which states are presented in the list.
  • Josh Mein
    Josh Mein about 12 years
    @Susan I think we need to see your html then and a more thorough explanation of what you are trying to do. Your question as it stands is deceiving.
  • Kaf
    Kaf about 12 years
    You are getting ddlStateList as parameter to the method but not using it. Binding to ddlState....
  • Josh Mein
    Josh Mein about 12 years
    @ Indikaf I just copied her code for that chunk, but I will update my answer.
  • Susan
    Susan about 12 years
    I tried your suggesting of adding a SelectedIndexChanged event and storing the selected index to a session variable, but since the dropdownlist is only loaded on !IsPostBack, the dropdownlists are now empty.
  • Susan
    Susan about 12 years
    I'm not sure I understand you comment about why I'm getting a selectedindex of 0; it suggests to me that during the buttonSubmit I've lost the selectedindex and it is 0 because that is the default value.
  • Susan
    Susan about 12 years
    I'm not using ViewState; I'm using Session variables.
  • Krishna
    Krishna about 12 years
    The selected index for the drop down list is based on the value of the user selected item. So if you have all the items in ddlStateList with the same value, the control returns the first item with the user selected value. In your case that would be 0 - the first item.
  • Krishna
    Krishna about 12 years
    Now consider a case where the drop down list is defined as <asp:DropDownList ID="ddlTest" runat="server"> <asp:ListItem Text="List Item 1" Value="1"></asp:ListItem> <asp:ListItem Text="List Item 2" Value="0"></asp:ListItem> <asp:ListItem Text="List Item 3" Value="1"></asp:ListItem> <asp:ListItem Text="List Item 4" Value="0"></asp:ListItem> </asp:DropDownList> In this case if you select the third item, the selected index would be 0 and if you select the fourth item, the selected index would be 1. Hope this helps you.
  • Derrick
    Derrick about 12 years
    You can lose Sessions depending on where they are stored, load-balancing and application pool recycling.