Reputation: 4807
I am using C# and ASP.Net 3.5, and trying to get a "Yes" / "No" value from checkbox, rather than a True / False. Is there an easy way or do I need to do "if" statements?
Upvotes: 4
Views: 13525
Reputation: 6803
You can simulate the behaviour you want by using a ternary statement.
Something like
string answer = checkbox.Checked ? "Yes" : "No";
would do you perfectly.
If for some reason you want to get the actual Yes/No direct from the checkbox (and I can see no reason for this at all) then you could subclass the component and instead of true/false have it take strings. Seems a little silly to do that though as effectively the "yes"/"no" is a humanisation, for me also its less code to maintain to derive it this way and this is pretty standard.
Upvotes: 2
Reputation: 1147
How about adding a extension method to the CheckBox class for this:
public static class CheckBoxExtensions
{
public static string IsChecked(this CheckBox checkBox)
{
return checkBox.Checked ? "Yes" : "No";
}
}
Usage:
var checkBox = new CheckBox();
checkBox.Checked = true;
Console.WriteLine(checkBox.IsChecked());
// Outputs: Yes
Upvotes: 5
Reputation: 1080
Just to give you a no if statement alternative (probably not the best approach in this case, but...):
Dictionary<Boolean, String> strings = new Dictionary<Boolean, String>();
strings.Add(true, "Yes");
strings.Add(false, "No");
Then when you need the value:
String yesNo = strings[checkbox.Checked];
Upvotes: 0
Reputation: 3965
sure try this:
string doesThisWork = chkBox.Checked ? "Yes":"No"
Upvotes: 10
Reputation: 888047
You can use the conditional operator:
checkbox.Checked ? "Yes" : "No"
If you want to be clever, you can use a dictionary:
static readonly Dictionary<bool, string> BooleanNames = new Dictionary<bool, string> {
{ true, "Yes" },
{ false, "No" }
};
BooleanNames[checkbox.Checked]
However, you really shouldn't.
Upvotes: 0
Reputation: 21905
I presume you are using an asp.net checkbox control and looking at the 'Checked' property. If so, you need a statement to translate the boolean value to yes/No:
string yesNo = checkbox_control.Checked ? "Yes" : "No";
Upvotes: 0