user279521
user279521

Reputation: 4807

ASP.Net checkbox to return a "Yes" or "No" value (instead of True / False)

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

Answers (8)

Pawel
Pawel

Reputation: 48

string doesThisWork = (bool)chkBox.Checked ? "Yes":"No"

Upvotes: 0

krystan honour
krystan honour

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

geeTee
geeTee

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

brian
brian

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

Luiscencio
Luiscencio

Reputation: 3965

sure try this:

string doesThisWork = chkBox.Checked ? "Yes":"No"

more info...

Upvotes: 10

SLaks
SLaks

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

Ray
Ray

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

Spencer Ruport
Spencer Ruport

Reputation: 35117

string YesNo = chkYesNo.Checked ? "Yes" : "No";

Upvotes: 1

Related Questions