Boolean Format String - Yes/No instead of True/False

Rate It (1)

Last post 08-20-2009 2:46 AM by Beginner1273. 32 replies.

Sort Posts:

  • Boolean Format String - Yes/No instead of True/False

    06-27-2007, 11:51 AM
    • Member
      point Member
    • Vader82
    • Member since 06-27-2007, 3:28 PM
    • Posts 2

    There exist quite a variety of built-in format strings for the various types in the .NET runtime.  For integers, decimals, floats, dates, etc things are quite happy as you can build up exactly the format you're looking for quite quickly.  But the built-in formatting for boolean values are simply true/false.  From a boolean algebra perspective, thats all anyone should ever need.  But if you're working with preferences-type information (email a customer when a specific even occurs, does a particular item have a particular feature) boolean values can indicate more of yes/no type data rather than true/false.  Sematically they're the same, but in terms of "looking right" yes/no is "more correct"

     Currently in order to get this feature in a datagrid I need to do several things:

    1.  Create a template column with a blank label

     <asp:TemplateColumn HeaderText="Preference">
        <ItemTemplate >
            <ASP:Literal id="myPreferenceInstance" runat="server" />
        </ItemTemplate>
    </asp:TemplateColumn>

    2.  Create an event handler that runs for every row in the datagrid which finds the control and inserts the appropriate yes/no string.

            public void DoExtraBinding(object sender, DataGridItemEventArgs e)
            {
                if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
                {

                    bool somepreference = DBConv.ToBoolean(DataBinder.Eval(e.Item.DataItem, "PreferenceFromDataBaseTable"));
               
                    Literal myPreferenceInstance= (Literal)e.Item.FindControl("myPreferenceInstance");
                   
                    if(somepreference)
                        myPreferenceInstance.Text = "Yes";
                    else
                        myPreferenceInstance.Text = "No";
               
                }
            }
     

    While I realize that this is a solution, and that a better one might exist, I haven't been able to find it.  What would be really elegant, however, is this:

    <Asp:BoundColumn HeaderText="Preference" DataField="PreferenceFromDataBaseTable" DataFormatString="{0:yn}" />

     

    This is of course, assuming that {0:yn} is the particular syntax necessary in order to achieve printing of yes/no rather than true/false based upon the value of the variable.

    I did some research into trying to do this myself by writing some custom formatting strings and formatting providers, but from my rather limited understanding of how all that works, it didn't seem like I would be able to actually use the custom formatting string within an ASP.NET page unless it was built into the framework somehow, and I don't know enough about the internals of ASP.NET to do that myself.

     I hope this snippet makes it to the right developer at Microsoft who can do something to make our lives out here in the trenches a bit easier.

    Thanks,

    Mike Sandford
     

  • Re: Boolean Format String - Yes/No instead of True/False

    06-27-2007, 2:14 PM
    • Member
      point Member
    • Vader82
    • Member since 06-27-2007, 3:28 PM
    • Posts 2

    I think there might be a few other potentially useful format strings as well:

    1 or 0

    High or Low (more from a hardware viewpoint)

    or possibly even just a generic "{0:string_if_true:string_if_false}" or something along those lines would be helpful for all the cases where we want a mutually exclusive representation where it might not necessarily be true/false from a presentation standpoint.
     

  • Re: Boolean Format String - Yes/No instead of True/False

    07-30-2007, 11:54 PM
    Answer
    • Contributor
      4,447 point Contributor
    • worldspawn[]
    • Member since 01-19-2003, 6:21 PM
    • Melbourne, Australia
    • Posts 942

    Had this same need. Writing custom formatters is pretty easy!! MS Slackers!

    Note this has ZERO localisation support, also I'm not sure how u tell ur databinding stuff to use the custom format provider. In my scenario i'm using it with string.Format calls so I haven't faced that issue.

    Enjoy...

        public class BoolFormatProvider : IFormatProvider, ICustomFormatter
        {
            #region ICustomFormatter Members

            public string Format(string format, object arg, IFormatProvider formatProvider)
            {
                bool value = (bool)arg;
                format = (format == null ? null : format.Trim().ToLower());

                switch (format)
                {
                    case "yn":
                        return value ? "Yes" : "No";
                    default :
                        if (arg is IFormattable)
                            return ((IFormattable)arg).ToString(format, formatProvider);
                        else
                            return arg.ToString();
                }
            }

            #endregion

            #region IFormatProvider Members

            public object GetFormat(Type formatType)
            {
                if (formatType == typeof(ICustomFormatter))
                    return this;
                else
                    return null;
            }

            #endregion
        }

     

    -- Sam Critchley

    "Wise man say 'forgiveness is divine, but never pay full price for late pizza." - TMNT

    website design
    internet marketing
  • Re: Boolean Format String - Yes/No instead of True/False

    08-14-2007, 1:28 AM
    Answer

    Quick and dirty in a DataBound ItemTemplate:

     <%# Eval("field").ToString() == "1" ? "Yes": "No" %>

  • Re: Boolean Format String - Yes/No instead of True/False

    12-04-2007, 4:08 PM
    • Star
      12,857 point Star
    • Motley
    • Member since 10-14-2005, 5:26 PM
    • West Chicago, IL
    • Posts 2,297
    • TrustedFriends-MVPs

    This should work as well:

    <%# CDbl(Eval("field")).ToString("No;Yes") %>

  • Re: Boolean Format String - Yes/No instead of True/False

    12-04-2007, 8:41 PM
    • Contributor
      4,447 point Contributor
    • worldspawn[]
    • Member since 01-19-2003, 6:21 PM
    • Melbourne, Australia
    • Posts 942

    Can't see how that would work in the case of a bool as the the double of a bool is either 0 or 1. Never -1.

     

    Edit:
    Multiplying it by -1 would make it work i suppose
     

    -- Sam Critchley

    "Wise man say 'forgiveness is divine, but never pay full price for late pizza." - TMNT

    website design
    internet marketing
  • Re: Boolean Format String - Yes/No instead of True/False

    05-28-2008, 12:10 PM
    • Member
      15 point Member
    • chihuachsund
    • Member since 04-29-2008, 8:21 PM
    • Posts 46

    I tried supernaturalgroups solution: <%# Eval("field").ToString() == "1" ? "Yes": "No" %>

    But I got syntax errors.  It would underline the second "=" and tell me "Expression Expected",  then if I removed it, it would bark at me about the question mark, and that the "No" was invalid syntax.  Does anyone know of any (good) documentation on the syntax of this? I'm pretty new to asp programming.

    I solved it by putting a Case statement in my selectcommand for my SqlDataSource (thanks to sbakshi in my other post: http://forums.asp.net/p/1263170/2375650.aspx#2375650)

    SelectCommand="SELECT *, Case When Active = 1 then 'Active' Else 'Inactive' End as Active1 FROM Onboarding_CellPhoneBBAdmin WHERE ItemType=@ItemType AND RecordType=@RecordType "

    then in my ItemTemplate, used that value:

    <asp:TemplateField HeaderText="Active?" HeaderStyle-HorizontalAlign="Center" ItemStyle-HorizontalAlign="Center">

    <ItemTemplate><%#Eval("Active1")%></ItemTemplate>

    <EditItemTemplate>

     

    <asp:DropDownList ID="ddlActive" runat="server" SelectedValue='<%# Bind("Active") %>'>

    <asp:ListItem Text="Active" Value="True" />

    <asp:ListItem Text="Inactive" Value="False" />

    </asp:DropDownList>

    </EditItemTemplate>

    </asp:TemplateField>

     

  • Re: Boolean Format String - Yes/No instead of True/False

    05-28-2008, 8:13 PM
    • Contributor
      4,447 point Contributor
    • worldspawn[]
    • Member since 01-19-2003, 6:21 PM
    • Melbourne, Australia
    • Posts 942

    The x ? y : z thing is called the ternary operator. Its a language feature of C# (well any c based language) and I suspect you are using visual basic hence your problems.

    -- Sam Critchley

    "Wise man say 'forgiveness is divine, but never pay full price for late pizza." - TMNT

    website design
    internet marketing
  • Re: Boolean Format String - Yes/No instead of True/False

    05-29-2008, 9:14 AM
    • Member
      15 point Member
    • chihuachsund
    • Member since 04-29-2008, 8:21 PM
    • Posts 46

    Thanks for the response, you are correct.  Is there an equivalent for VB? 

  • Re: Boolean Format String - Yes/No instead of True/False

    05-30-2008, 12:28 AM
    • Contributor
      4,447 point Contributor
    • worldspawn[]
    • Member since 01-19-2003, 6:21 PM
    • Melbourne, Australia
    • Posts 942

    Yeah...

    If(True, "TruePart", "FalsePart")

     

    -- Sam Critchley

    "Wise man say 'forgiveness is divine, but never pay full price for late pizza." - TMNT

    website design
    internet marketing
  • Re: Boolean Format String - Yes/No instead of True/False

    05-30-2008, 10:26 AM
    • Member
      15 point Member
    • chihuachsund
    • Member since 04-29-2008, 8:21 PM
    • Posts 46

    I still get an "End of Statement Expected Error when I try this:

     

    <ItemTemplate><%#Eval("Active").ToString If(True, "Active", "Inactive")(%></ItemTemplate>

     

    Obviously, I am missing something.  Where can I go to find documentation about this functionality?  I don't even know what it's called.  I dug through ItemTemplates, EditItemTemplates, etc, but couldn't find how to use the <%Eval %> syntax.

  • Re: Boolean Format String - Yes/No instead of True/False

    05-30-2008, 10:32 AM
    • Member
      15 point Member
    • chihuachsund
    • Member since 04-29-2008, 8:21 PM
    • Posts 46

    Just noticed the extra open parentheses in my statement, but it didn't fix anything.

  • Re: Boolean Format String - Yes/No instead of True/False

    05-30-2008, 10:51 AM
    • Contributor
      6,676 point Contributor
    • ramblor
    • Member since 03-13-2008, 10:03 AM
    • Posts 1,013

    Try this:

    <ItemTemplate><%# IIf(Eval("Active"), "Active", "Inactive") %></ItemTemplate>

    Note the function you use is IIF, not IF. 

     

    "Sometimes I think the surest sign that intelligent life exists elsewhere in the universe is that none of it has tried to contact us."
  • Re: Boolean Format String - Yes/No instead of True/False

    05-30-2008, 12:32 PM
    • Member
      15 point Member
    • chihuachsund
    • Member since 04-29-2008, 8:21 PM
    • Posts 46

    BINGO!

     Where can I find documentation on these? I finally found some info on the Eval function, but it didn't include any references to IIF, etc. 

  • Re: Boolean Format String - Yes/No instead of True/False

    06-02-2008, 8:15 PM
    • Contributor
      4,447 point Contributor
    • worldspawn[]
    • Member since 01-19-2003, 6:21 PM
    • Melbourne, Australia
    • Posts 942

    IIF is not a true ternary operator. Replacing IIF with just IF should also work and will be a true ternary operator. If you use IIF both the true and false expression will be evaluated, which is some scenarios may cause errors.

    Documentation is found in the MSDN library, which you should have installed when u installed visual studio (but is also available online @ http://msdn.microsoft.com/en-gb/library/default.aspx).
     

    -- Sam Critchley

    "Wise man say 'forgiveness is divine, but never pay full price for late pizza." - TMNT

    website design
    internet marketing
Page 1 of 3 (33 items) 1 2 3 Next >