In this example, we are going to be adding a list of names to a ListBox and figure out which names have a check next to them and which don't. We will also see how to set the IsChecked property of a CheckBox using code
string[] names = new[] {"Susan", "John", "Andrew", "Bob", "Raphael", "Sam"};
foreach (var name in names)
{
CheckBox checkBox = new CheckBox();
checkBox.Content = name;
checkBox.IsChecked = name.Contains('a'); // Place a check next to names containing an 'a'
//checkBox.Click += checkBox_Click;
ListBox1.Items.Add(checkBox);
}
It's seriously that simple. However, this probably isn't useful if you can't pull any data out of it. Finding which boxes are checked and which aren't is just as simple using LINQ.
string[] GetSelectedNames()
{
List selectedNames= new List();
var checkedCheckBoxes = from CheckBox checkBox in ListBox1.Items
where checkBox.IsChecked == true
select checkBox;
foreach (var name in checkedCheckBoxes)
{
selectedNames.Add(name.Content + Environment.NewLine);
}
return selectedNames.ToArray();
}
Here is a sample: