1

I have a Program Class, with properties as Id, ProgramName,ShortName and Code, im my app I have a ASP DDL like

<asp:DropDownList ID="DDLProgram" runat="server" 
            OnSelectedIndexChanged ="OnDDLProgramChanged" AutoPostBack = "true">
    </asp:DropDownList>

My OnDDLProgramChanged method is defined as

protected void OnDDLProgramChanged(object sender, EventArgs e)
        {
            List<CcProgramEntity> programEntities = GetAllPrograms();

            DDLProgram.DataSource = programEntities;
            DDLProgram.DataTextField = "Shortname";
            DDLProgram.DataValueField = "Id";

            //My Problem goes here
            string programCode = programEntities[DDLProgram.SelectedIndex].Code;
        }

My list is getting all the records correctly, I have checked it. But whenever I am changing an item in the DDL, the selected index in not changing. The selected index is remaining zero.Therefore, I am not being able to get the code of other items but the 0 index's item.

Can anyone help me in this case?

1
  • Do you have IsPostBack check in your page_load ?
    – V4Vendetta
    Jul 5, 2011 at 5:21

3 Answers 3

3

You are binding the data again in your selectedIndex Change event and it will reset your current SelectedIndex after rebinding. You don't need to rebind the data to your dropdown in SelectedIndex Change Event

It should be like..

protected void OnDDLProgramChanged(object sender, EventArgs e)
    {

        string programCode = programEntities[DDLProgram.SelectedIndex].Code;
    }
1
  • Thank you for your kind suggesion, I have modified my code, Now it is looking much neater and cleaner
    – Pankouri
    Jul 5, 2011 at 8:30
3

You have to bind data to the DropDownList on page load method

if (!IsPostBack)
{
    DDLProgram.DataSource = programEntities;
    DDLProgram.DataTextField = "Shortname";
    DDLProgram.DataValueField = "Id";
    DDLProgram.DataBind();
}

Otherwise it will bind data everytime and hence clear the selection

2
  • @Eranga: Thanx for the Solution, it worked perfectly for me. But now its Happening only when I am Changing the Item. What If I Want to make it work for the first time the page is loaded? I have More tha n one DDL in my page and I am binding all of them by a method Bind DDLs(). I am calling this M<ethod inside the if(!IsPostBack) condition of pageload method
    – Pankouri
    Jul 5, 2011 at 7:17
  • @Pankouri What do you mean by its Happening only when I am Changing the Item? are you the drop down list in OnDDLProgramChanged?
    – Eranga
    Jul 5, 2011 at 7:26
1

Why are you assigning the DataSource in OnDDLProgramChanged, this would be resetting the selection you make.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.