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.CheckedIndicesproperty. From there, you can get to the individual item and find the appropriate value from it. WhileDisplayMemberworks, 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 forCheckedListBox.ValueMemberclaim that it’s “not relevant to this class”.