Chris Jones
Chris Jones

Reputation: 2746

Get ValueMembers of a CheckBoxList

I have a linq Query that I have bound to a Checkbox list using Windows forms

var webresourcesFromCRM = from w in orgSvcContext.CreateQuery("webresource")                                                   
                          select new
                          {
                              webresourceid = w["webresourceid"],
                              name = w["name"]
                          };

I have used the DisplayMember and ValueMember properties when binding

cblWebResources.DataSource = webresourcesFromCRM;
cblWebResources.DisplayMember = "name";
cblWebResources.ValueMember = "webresourceid";

the above code works great. However My problem is I want to get the ValueMember of the checked items. I've tried every combination of cblWebResources.SelectedItems or cblWebResources.SelectedIndices. I just want to be able to loop through my selected items and out put each ValueMember in a windows form app.

I've try other posts like but no luck this is a windows form app

var selectedItems = checkedUsers.Items.Cast<ListItem>()
                                      .Where(li => li.Selected)
                                      .Select(li => int.Parse(li.Text));
int sum = selectedItems.Sum();
string items = string.Join(",", selectedItems);

Upvotes: 1

Views: 856

Answers (2)

Chris Jones
Chris Jones

Reputation: 2746

I needed to cask my checked items to an object

foreach (var item in cblWebResouces.CheckedItems.Cast()) { MessageBox.Show(item.webresourceid); }

Upvotes: 0

TaW
TaW

Reputation: 54433

A CheckedListBox conveniently has both:

 var c = checkedListBox1.CheckedItems;
 var s = checkedListBox1.SelectedItems;

Now you get the intersection:

var cs = c.Cast<object>().Where(i => s.Contains(i));
var sc = s.Cast<object>().Where(i => c.Contains(i));

Sadly CheckedListBoxes don't support MultiSelect, so the second form should be better.

What it sadly also doesn't have is an option to bind the Checkboxes :-(

Upvotes: 4

Related Questions