11
votes

I have this code for casting CheckedListBox.Items to List<Item>:

List<Item> items = ChkLsBxItemsToDraw.Items as List<Item>;

and this is my Item Class

public class Item
{
    public List<double> x = new List<double>();
    public List<double> y = new List<double>();
}

I set CheckedListBox.DataSource to a List<Item>

and I got this Error:

Error 1 Cannot convert type 'System.Windows.Forms.CheckedListBox.ObjectCollection' to 'System.Collections.Generic.List<Drower.Item>' via a reference conversion, boxing conversion, unboxing conversion, wrapping conversion, or null type conversion

How Can I get the CheckedListBox.Items as List<Item> ???

3
What is going wrong? What is the error? - Oded

3 Answers

17
votes

The DataSource and the Items properties are unrelated. The fact that you set the first property doesn't mean that you will get anything in the second. For example if you check the number of items it will be 0: ChkLsBxItemsToDraw.Items.Count.

You could add elements to the Items property:

List<Item> items = ...
ChkLsBxItemsToDraw.Items.AddRange(items.ToArray());

and later retrieve them back as a list:

List<Item> items = ChkLsBxItemsToDrawItems.Cast<Item>().ToList();
6
votes
List<Item> items = this.ChkLsBxItemsToDraw.Items.Cast<Item>().ToList();
2
votes
public class Item
{
    public List<double> x = new List<double>();
    public List<double> y = new List<double>();
}

static void Main(string[] args)
{
    CheckedListBox box = new CheckedListBox();
    box.Items.OfType<Item>().ToList();
}