ListBox not getting selected items

六月ゝ 毕业季﹏ 提交于 2019-12-05 08:06:41

The problem is that you call PopulateDropDown() on every single Page_Load(), which calls PopulateListBox(), which clears the listbox and repopulates it. By clearing the listbox, you clear the selection.

You need to replace your call to PopulateDropDown() in the Page_Load() with the following code. The issue that I think you don't realize is that the page is loaded on every postback -- and that in the page life cycle, the page load occurs before the event. So by selecting a drop down item, you execute the Page_Load() event first (which indirectly executes the LoadListBox method, clearing the selection). The following code will populate the drop down list the first time the page loads only. Keep it the same wherever else you are using the load dropdown method:

protected void Page_Load(object sender, EventArgs e)
{
    // Do your API code here unless you want it to occur only the first
    // time the page loads, in which case put it in the IF statement below.
    if (!IsPostBack)
    {
        PopulateDropDown();
    }
}

The IsPostBack returns a boolean indicating whether the server side code is running because the page is loading for the first time ("false") or as a post back ("true").

As I said elsewhere, keep in mind that a listbox with potential for multiple selected values must be handled differently than one with potential for a single selection. Don't reference listbox.SelectedItem, but rather:

foreach (ListItem item in lbFullNames)
{
    if (item.Selected)
    {
        // TODO: Whatever you are doing with a selected item.
    }
}

I have also found that if you disable the ListBox server-side, then use client side code to enable the list box using code like the following, then you cannot get the selected items server side.

$('.css-class-assigned-to-listbox').attr('disabled', '');

The fix is simply to make sure it is enabled server-side (the default), then disable it (see blow) or enable it (see above) using client-side code.

$('.css-class-assigned-to-listbox').attr('disabled', 'disabled');
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!