I have four checkboxes in my form. I have string variable called "CheckedString". If i check the first checkbox "A" must be assigned to "CheckedString". If i select both first and second checkbox at a time. "AB" must be assigned to "CheckedString". If i select third and fourth checkbox "CD" must be assigned to "CheckedString".So that several combination exists. How to implement this in C sharp. Please help?
5 Answers
Pseudocode since my VS2008 is currently in a "hosed" state and I can't check:
string CheckedString = ""
if checkbox a is set:
CheckedString += "A"
if checkbox b is set:
CheckedString += "B"
if checkbox c is set:
CheckedString += "C"
if checkbox d is set:
CheckedString += "D"
Voila! There you have it. You simply append the value for each checkbox in order.
1 Comment
paxdiablo
@RC, if you translate it into C#, I'll upvote you. It's just that my VS2008 crashed on me yesterday and I haven't had a chance to re-install yet. Stuff it, I think I'll just nick out and get VS2010.
Go with paxdiablo. For a more 'general' solution, you can do something like this in LINQ (assuming you have the checkboxes in an array):
var chars = Enumerable.Range(0, checkBoxes.Length) // 0, 1, 2, 3
.Where(i => checkBoxes[i].Checked) // 0, 2
.Select(i => (char)('A' + i)); // A, C
var myString = new string(chars.ToArray()); // "AC"
or, with a for-loop:
var sb = new StringBuilder();
for (int i = 0; i < checkBoxes.Length; i++)
{
if (checkBoxes[i].Checked)
sb.Append((char)('A' + i));
}
var myString = sb.ToString();
Comments
Here they way write in C# and using function (reusability):
string CheckedString = string.Empty;
CheckedString += AssignCheckBox(chkBoxFirst, "A");
CheckedString += AssignCheckBox(chkBoxSecond, "B");
CheckedString += AssignCheckBox(chkBoxThird, "C");
CheckedString += AssignCheckBox(chkBoxFourth, "D");
And the function is:
public string AssignCheckBox(CheckBox chk, string strSet)
{
return chk.Checked ? strSet : string.Empty;
}