简体   繁体   中英

SelectedIndex is not changing SharePoint asp DropDownList

I am writing a SharePoint App and have a problem with drop down list. Its SelectedIndex is not changing. I read many questions and answers and they suggest using IsPostBack or EnableViewState to true . I did both with no success.

ASP code:

<div class="value">
    <asp:DropDownList ID="groupingDropDownList" runat="server" EnableViewState="True" OnSelectedIndexChanged="groupingDropDownList_SelectedIndexChanged" AutoPostBack="true" />
</div>

C# code:

protected void Page_Load(object sender, EventArgs e)
{
    if (!Page.IsPostBack)
            {                
                groupingDropDownList.DataSource = sourceList.Select(x => new { x.Name, Value = x });
                groupingDropDownList.DataTextField = "Name";
                groupingDropDownList.DataValueField = "Value";
                groupingDropDownList.DataBind();
            }
}

Event SelectedIndexChanged is not firing because index is not changing. I set a breakpoint on line if (!Page.IsPostBack) and it is always 0.

In the !Page.IsPostBack block you are populating your dropdown for the first time. You seem to be trying to detect a change in the dropdown selection as it is loading - which is impossible.

So, to test it you should do a check in the postback of the page or in the groupingDropDownList_SelectedIndexChanged event handler.

if (!Page.IsPostBack)
{                
    groupingDropDownList.DataSource 
        = sourceList.Select(x => new { x.Name, Value = x });
    groupingDropDownList.DataTextField = "Name";
    groupingDropDownList.DataValueField = "Value";
    groupingDropDownList.DataBind();
}
// Actual postback
else
{
    var test = groupingDropDownList.SelectedValue;
}

I know what was my mistake, it was the line:

groupingDropDownList.DataSource = sourceList.Select(x => new { x.Name, Value = x });

I always set value equal to class name and since the value didn't change, the control didn't notice index change.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM