How to get the CheckedListBox Selected Items into List<X>...?
Asked Answered
B

5

9

I am having a List of type X. X is a Property Level Class. Now on an event i need the CheckedListBox Selected Items into another List.

How to get the output...?? The code i tried is given below...

public void Initialize(List<X> x1)
{
        chkList.DataSource = x1;
        chkList.DisplayMember = "MeterName"; // MeterName is a property in Class X
        chkList.ValueMember = "PortNum"; // PortNum is a property in Class X
}

private void Click_Event(object sender, EventArgs e)
{

List<X> x2 = new List<X>();
// Here I want to get the checkedListBox selected items in x2;
// How to get it...???

}
Basalt answered 19/12, 2012 at 5:8 Comment(1)
Possible duplicate of Casting an Item Collection from a listbox to a generic listHorrify
V
23

you can try the following

 List<X>  x2 =  chkList.CheckedItems.OfType<X>().ToList();

or cast as object

List<object>  x2 = chkList.CheckedItems.OfType<object>().ToList();
Vergos answered 19/12, 2012 at 5:17 Comment(3)
+1 this works fine, I see no reason to add my foreach based answer :)Italia
actually i am using DevExpress so the above solution wont work there. But it gave me a spark to get my solution... tanx buddy..Basalt
@RavishankarN you can use Cast instead of OfType to get this working.Forefinger
R
2

Here is a way that works for me:

List<X> x2 = new List<X>();
x2 = chkList.CheckedItems.Cast<X>().ToList();
Rostand answered 16/8, 2013 at 15:42 Comment(0)
B
1

i got the answer

private void Click_Event(object sender, EventArgs e)
{

List<X> x2 = new List<X>();
foreach (X item in chkList.CheckedItems)
    {
        x2.Add(item);
    }
}
Basalt answered 19/12, 2012 at 5:30 Comment(0)
B
0
string[] miList = chkList.CheckedItems.OfType<object>().Select(li => li.ToString()).ToArray();
Britisher answered 30/12, 2014 at 16:33 Comment(0)
F
0

This is another Option

List<X> lst = new List<X>(chkList.CheckedItems.Cast<X>());
Fermi answered 19/11, 2016 at 8:39 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.