开发者

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?


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


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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜