Pankouri
Pankouri

Reputation: 676

selected index of DDL is always equal to Zero in asp .net

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?

Upvotes: 1

Views: 2363

Answers (3)

Muhammad Akhtar
Muhammad Akhtar

Reputation: 52241

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

Upvotes: 3

V4Vendetta
V4Vendetta

Reputation: 38210

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

Upvotes: 1

Eranga
Eranga

Reputation: 32437

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

Upvotes: 3

Related Questions