ebooyens
ebooyens

Reputation: 628

Populating selected value property for CheckedListBox

I'm using a CheckedListBox (System.Windows.Forms.CheckListBox) and running through some code to populate items in the list using a DataSet. My problem is that I can't seem to figure out how to set the Selected Value property, or find the right property to set!

Here's my code that successfully adds in the items:

for (int i = 0; i < projectsDataSet.tblResources.Rows.Count; i++)
{
   clbResources.Items.Add(projectsDataSet.tblResources.Rows[i]["Description"].ToString());
}

There are no useful overloads on the .Add method that takes a value parameter and I can't seem to get to a value property of an item.

I guess the bottom line of what I need is the items in the CheckedListBox to display items using one field from my DataSet (like a description) and use another to store that item's value (like a primary key), so would appreciate suggestions to achieve that, thanks!

Upvotes: 1

Views: 2219

Answers (2)

paul
paul

Reputation: 22001

First make a class for your list box items...

public class Thing
{
    public string Key { get; set; }
    public string Value { get; set; }

    public override string ToString()
    {
        return Key + "--" + Value;
    }
}

Then add items to your CheckListBox like so:

for (int i = 0; i < projectsDataSet.tblResources.Rows.Count; i++)
{
   clbResources.Items.Add(new Thing()
   {
       Key = projectsDataSet.tblResources.Rows[i]["Key"].ToString(),
       Value = projectsDataSet.tblResources.Rows[i]["Description"].ToString()
   }, isChecked);
}

Upvotes: 2

Ronak Patel
Ronak Patel

Reputation: 2610

I had had the same issue. Luckily you there is workaround to this.

if the number of items and order of items in ListBox & DataTable is same then you can get the corresponding value as below

ListBox.SelectedIndexCollection items = checkedListBox1.SelectedIndices;

            for(int i=0;i<items.Count;i++)
                string selectedValue = projectsDataSet.tblResources.Rows[items[i]]["ValueColumn"].ToString();

Upvotes: 1

Related Questions