Subodh Bansal
Subodh Bansal

Reputation: 385

CheckedListBox checked items to object conversion?

I have a collection named Subjects with attributes as Name in string, 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...

Upvotes: 5

Views: 3718

Answers (2)

Hans Passant
Hans Passant

Reputation: 942070

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...
    }
}

Upvotes: 5

Richard J. Ross III
Richard J. Ross III

Reputation: 55583

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.

Upvotes: 0

Related Questions