How will I get the SelectedItem? C# winforms CheckedListBox control

Prior to this question, I asked this question on this site. (Mr Jon Skeet answered it!)

I'm having difficulty retrieving the SelectedItem of the CheckedListBox. Please consider my code:

public class StaticValues
    private string value;
    private string display;
    public StaticValues(string val, string disp)
        this.value = val;
        this.display = disp;

    public string Value
        { return value; }

    public string Display
        { return display; }

private void Form3_Load(object sender, EventArgs e)
    ArrayList dataSource = new ArrayList();
    dataSource.Add(new StaticValues("001", "Item 1"));
    dataSource.Add(new StaticValues("002", "Item 2"));
    dataSource.Add(new StaticValues("003", "Item 3"));
    checkedListBox1.DataSource = dataSource;
    checkedListBox1.DisplayMember = "Display";
    checkedListBox1.ValueMember = "Value";

private void button1_Click(object sender, EventArgs e)
    MessageBox.Show(checkedListBox1.SelectedValue.ToString()); // outputs correct SelectedValue 
    MessageBox.Show(checkedListBox1.SelectedItem.ToString()); // this one doesn't for SelectedItem

How will I get the SelectedItem?


Given that it's a list of check boxes, I suspect it would be better to find all the checked items using the CheckedListBox.CheckedIndices property. From there, you can get to the individual item and find the appropriate value from it. While DisplayMember works, I suspect you're better off casting the item to the known type and finding the value that way, unless that's really awkward for you. There may be another way round it, but I don't know of one. Note that the docs for CheckedListBox.ValueMember claim that it's "not relevant to this class".

Initially there is no selected item, at least until a user selects one. To retrieve a user selected value you must react to the wselectedIndexChanged event and if the user changes that value to the OnSelectedValueChanged event.

If you wish to find which items have their checkboxes set then you'll need to look at the CheckecItemCollection and CheckedIndexCollection properties.

Need Your Help

Count characters in two p's and trim in the second p if more than 290 characters?

jquery count

I'm rendering questions on a page with a title and content, and if the total number of characters (in both title and content) exceed 290 characters I want to trim the last x characters in the conte...