views:

92

answers:

5

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?

+3  A: 

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.

paxdiablo
was typing the same => +1
RC
@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.
paxdiablo
Thak you so much... great..!!!
Prem
+2  A: 

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();
Ani
Thank you very much
Prem
+1  A: 
string CheckedString = (cbxA.Checked ? "A" : "") + 
            (cbxB.Checked ? "B" : "") + 
            (cbxC.Checked ? "C" : "") + 
        (cbxD.Checked ? "D" : "");
Lee Sy En
Thank you very much!!!
Prem
+1  A: 

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;
}
Edy Cu
+2  A: 
string result = String.Format("{0}{1}{2}{3}", 
                  checkboxA.Checked ? "A" : string.Empty,
                  checkboxB.Checked ? "B" : string.Empty,
                  checkboxC.Checked ? "C" : string.Empty,
                  checkboxD.Checked ? "D" : string.Empty
                );
Dave Anderson