开发者

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

开发者 https://www.devze.com 2022-12-22 15:23 出处:网络
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\" statem开发者_如何学Goents?sure try t

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" statem开发者_如何学Goents?


sure try this:

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

more info...


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


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


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.


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


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.


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


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

0

精彩评论

暂无评论...
验证码 换一张
取 消