ASP.Net checkbox to return a "Yes" or "No" value (instead of True / False)
Solution 1
sure try this:
string doesThisWork = chkBox.Checked ? "Yes":"No"
Solution 2
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
Solution 3
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.
Solution 4
string YesNo = chkYesNo.Checked ? "Yes" : "No";
user279521
.Net developer in training; working on multiple projects at any given time (austink_2004);
Updated on July 10, 2022Comments
-
user279521 almost 2 years
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?
-
Doug Stalter over 14 yearsI am curious why you want to do this? Working with a boolean value is much easier than working with a string representing the same thing.
-
user279521 over 14 yearsThe value of the checkbox get displayed in a "Print This Page", and the client wants to see a "Yes / No" as opposed to a "True / False"
-
Luiscencio over 14 yearsClients like that "I-am-in-control" feeling
-
Doug Stalter over 14 yearsI assume you aren't persisting this data in any other place than the web page and thus you are rendering the "Print This Page" based on the control values instead of some other object that contains the data.
-
user279521 over 14 years@DougStalter: Correct, this is a simple data retrieve from db, user makes modifications, prints out the page; No saving to database;
-
user279521 over 14 years@Luiscencio:, I just do as I am told :-)
-
-
user279521 over 14 yearsPerfect solution. Thanks Luiscencio
-
Yunnosch over 3 yearsWhile this code may solve the question, including an explanation of how and why this solves the problem would really help to improve the quality of your post, and probably result in more up-votes. Remember that you are answering the question for readers in the future, not just the person asking now. Please edit your answer to add explanations and give an indication of what limitations and assumptions apply.