views:

367

answers:

3

can anybody show me how to build a string using checkbox. what would be the best way to do this.

for example i have 4 checkbox's each with its own value (valueA, valueB, valueC, valueD) the thing is i want to display each result in different lines.

result if B & C is selected :

valueB
valueC

and how would i display this again if i saved this into a database?

A: 
"if I saved this into a database" ?

You'll need to be a bit more specific with your homework assignments if you're actually going to receive any help here ...

Edit: ok, it might not be homework but it certainly read like it - after all, manipulating a GUI to generate a view of the user's choices is Interfaces 101 - and even it wasn't it was a terrible question without enough detail to have any chance of getting a decent answer.

Unsliced
@Unsliced: "without enough detail to have any chance of getting a decent answer" - what part of the question did my answer not cover? Yes, more detail would have been nice, but it really wasn't "terrible".
Jon Skeet
+4  A: 

Use a StringBuilder to build the string, and append Environment.NewLine each time you append:

StringBuilder builder = new StringBuilder();
foreach (CheckBox cb in checkboxes)
{
    if (cb.Checked)
    {
        builder.AppendLine(cb.Text); // Or whatever

        // Alternatively:
        // builder.Append(cb.Text);
        // builder.Append(Environment.NewLine); // Or a different line ending
    }
}
// Call Trim if you want to remove the trailing newline
string result = builder.ToString();

To display it again, you'd have to split the string into lines, and check each checkbox to see whether its value is in the collection.

Jon Skeet
@Jon - Why would you do the two appends rather than AppendLine(cb.Text)?
Carl
Due to failing to remember AppendLine - edited appropriately :)
Jon Skeet
(Having said which, it may be sensible to do two appends if you need a specific newline representation instead of "whatever's the default for this platform. Probably not an issue if you're always running on Windows though.)
Jon Skeet
Good, as long as you didn't know something that I didn't :) (Although, that is just a given to be honest!)
Carl
i don't get AppendLine (probably because im using vs2003) can u show the example using the two appends.
Adit
@Adyt: Added the alternative code back in. I hope you're campaigning to get up to VS2008 :)
Jon Skeet
+1  A: 

Pseudo-code:

For each checkbox in the target list of controls
    append value and a newline character to a temporary string variable
output temporary string
Unsliced