1

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 5

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

@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.
3
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
                );

Comments

2
string CheckedString = (cbxA.Checked ? "A" : "") + 
            (cbxB.Checked ? "B" : "") + 
            (cbxC.Checked ? "C" : "") + 
        (cbxD.Checked ? "D" : "");

Comments

2

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

1

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;
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.