开发者

C# checkbox to string question

开发者 https://www.devze.com 2022-12-18 22:32 出处:网络
I have 7 checkboxes.What I want is to make one string for开发者_JS百科 each of those checkboxs.Meaning if I had....

I have 7 checkboxes. What I want is to make one string for开发者_JS百科 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(';');
    }
}


What I usually do when wanting to concat strings with a given separator, is putting my strings in a string array, then use the String.Join method. Example :

string.Join(";", new string[] { "test1", "test2", "test3" }); // Which outputs test1;test2;test3


You could use something similar to:

List<CheckBox> boxes;
String result = String.Join(" ; ", boxes.Where(box => box.Checked)
                                        .Select(box => box.Text).ToArray());


var values = (from c in new[] { c1, c2, c3, c4, c5, c6, c7 }
              where c.Checked
              select c.Text).ToArray();
var result = string.Join(";", values);


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消