I have 7 checkboxes. What I want is to make one string for each of those checkboxs. Meaning if I had....
Orange apple pear plum grape tiger red
And orange pear and red where checked.
I'd get a string that produced "orange ; pear ; red"
I have 7 checkboxes. What I want is to make one string for each of those checkboxs. Meaning if I had....
Orange apple pear plum grape tiger red
And orange pear and red where checked.
I'd get a string that produced "orange ; pear ; red"
What is the problem, do you need just this?
StringBuilder sb = new StringBuilder();
foreach(var cb in checkBoxes)
{
if(cb.IsChecked)
{
sb.Append(cb.Text);
sb.Append(';');
}
}
You didn't specify WinForms versus WPF; I will assume WinForms but code is nearly identical for WPF (replace Checked by IsChecked and Text by Tag). The CheckBox control has a Checked property indicating whether or not the CheckBox is in the checked state. So say that you CheckBoxes are in an array CheckBox[] checkBoxes. Then you could say
List<string> checkedItems = new List<string>();
for(int i = 0; i < checkBoxes.Length; i++) {
CheckBox checkBox = checkBoxes[i];
if(checkBox.Checked) {
checkedItems.Add(checkBox.Text);
}
}
string result = String.Join(" ; ", checkedItems.ToArray());
Of course, that imperative and yucky. Let's get happy with some nice declarative code in LINQ:
string result = String.Join(
" ; ",
checkBoxes.Where(cb => cb.Checked)
.Select(cb => cb.Text)
.ToArray()
);
If your CheckBoxes are not in array, you could start by putting them in array via
CheckBox[] checkBoxes = new[] { c1, c2, c3, c4, c5, c6, c7 };
where c1, c2, ..., c7 are your CheckBoxes.