Tutorial :ASP.Net checkbox to return a “Yes” or “No” value (instead of True / False)



Question:

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?


Solution:1

sure try this:

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

more info...


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

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


Solution:4

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:5

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


Solution:6

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.


Solution:7

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

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »