简体   繁体   中英

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
    {
        get
        { return value; }
    }

    public string Display
    {
        get
        { 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM