开发者

CheckedListBox checked items to object conversion?

开发者 https://www.devze.com 2023-01-28 17:03 出处:网络
I have a collection named Subjects with attributes as Name in st开发者_JS百科ring, and SubjectCode in int. I passed it to a checked list box. On the press of a button, i want to get the collection of

I have a collection named Subjects with attributes as Name in st开发者_JS百科ring, and SubjectCode in int. I passed it to a checked list box. On the press of a button, i want to get the collection of all the items checked by user, convert it as the collection Subjects.

Plz anyone could help....

Thnx in advance...


A CheckedListBox can store any kind of class object. You just need a ToString() override that shows the description of the object. For example:

    class Subject {
        public string Name { get; set; }
        public int Code { get; set; }
        public override string ToString() { return Name; }
    }

You can add these to the Items collection. Reading back the selected ones just takes casting the object back to Subject. For example:

public partial class Form1 : Form {
    public Form1() {
        InitializeComponent();
        checkedListBox1.Items.Add(new Subject { Name = "Hans", Code = 42 });
        checkedListBox1.Items.Add(new Subject { Name = "User", Code = 486196 });
    }

    private void button1_Click(object sender, EventArgs e) {
        var selected = new List<Subject>();
        foreach (int index in checkedListBox1.SelectedIndices) {
            selected.Add((Subject)checkedListBox1.Items[index]);
        }
        // etc...
    }
}


How about this?

Subject[] myObjects;

void onButtonPressed(object sender, EventArgs e)
{
      foreach (int i in this.checkedItems.CheckedIndecies)
      { 
           Subject obj = myObjects[i];
      }
}

You can directly access the objects, but you risk the scenario where the objects in the listBox aren't of type subject, and it gives you more extendability in the future.

0

精彩评论

暂无评论...
验证码 换一张
取 消