Listbox - if (item.selected) not responding as expected

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • ewalsh9898
    New Member
    • Aug 2015
    • 1

    Listbox - if (item.selected) not responding as expected

    while processing the items in a listbox foreach loop, the if (item.selected) never finds expected row(s)

    The foreach is looping thru the data as expected.

    Code:
    <asp:ListBox runat="server" ID="lstFrom" Width="250" Height="200" SelectionMode="Multiple"></asp:ListBox>
    <asp:ListBox runat="server" ID="lstTo" Width="250" Height="200" SelectionMode="Multiple"></asp:ListBox>
    
    protected void btnSelectOne_Click(object sender, EventArgs e)
        {
            MoveSelectedItem(lstFrom, lstTo);
        }
    
    private void MoveSelectedItem(ListBox fromListBox, ListBox toListBox)
        {
            List<ListItem> selected = new List<ListItem>();
    
            foreach (ListItem item in fromListBox.Items)
            {
                if (item.Selected) selected.Add(item);          // this is not being hit
            }
        }
    Last edited by Rabbit; Aug 27 '15, 08:07 PM. Reason: Please use [code] and [/code] tags when posting code or formatted data.
  • Kara Hewett
    New Member
    • Apr 2014
    • 27

    #2
    A few problems could cause the if(item.selecte d) line to not be hit:

    1. The code snippet doesn't demonstrate where fromListBox is initialized with values.
    2. The data type is not correctly identified. Perhaps use a var type such as

    foreach (var item in fromListBox.Ite ms)
    {
    if (item.Selected) selected.Add(it em);
    }

    Comment

    Working...