Get all selected items from asp.net ListBox

后端 未结 3 872
梦毁少年i
梦毁少年i 2021-02-07 12:19

Anyone know of a smooth way to get all of the selected items in a listbox control by using extension methods?

And, please, spare me the argument of

3条回答
  •  轮回少年
    2021-02-07 12:50

    Extension method:

    public static List GetSelectedItems(this ListBox lst)
    {
        return lst.Items.OfType().Where(i => i.Selected).ToList();
    }
    

    You can call it on your listbox like:

    List selectedItems = myListBox.GetSelectedItems();
    

    You could also do the conversion using a 'Cast' on the list box items like:

    return lst.Items.Cast().Where(i => i.Selected).ToList();
    

    Not sure which will perform better OfType or Cast (my hunch is Cast).

    Edit based on Ruben's feedback for a generic ListControl method which would indeed make it much more useful extension method:

    public static List GetSelectedItems(this ListControl lst)
    {
        return lst.Items.OfType().Where(i => i.Selected).ToList();
    }
    

提交回复
热议问题