68

I have a ASP.NET GridView with a column mapped to a boolean. I want do display "Yes"/"No" instead of "True"/"False". Well actually I want "Ja"/"Nej" (in Danish).

Is this possible?

<asp:gridview id="GridView1" runat="server" autogeneratecolumns="false">
    <columns>
        ...
        <asp:boundfield headertext="Active" datafield="Active" dataformatstring="{0:Yes/No}" />
        ...
    </columns>
</asp:gridview>
piet.t
  • 11,718
  • 21
  • 43
  • 52
Thomas Jespersen
  • 11,493
  • 14
  • 47
  • 55

9 Answers9

136

I use this code for VB:

<asp:TemplateField HeaderText="Active" SortExpression="Active">
    <ItemTemplate><%#IIf(Boolean.Parse(Eval("Active").ToString()), "Yes", "No")%></ItemTemplate>
</asp:TemplateField>

And this should work for C# (untested):

<asp:TemplateField HeaderText="Active" SortExpression="Active">
    <ItemTemplate><%# (Boolean.Parse(Eval("Active").ToString())) ? "Yes" : "No" %></ItemTemplate>
</asp:TemplateField>
travis
  • 35,751
  • 21
  • 71
  • 94
  • Thanks! ☺ I actually marked this question as a fave so that I can reference (eg copy/paste) those snippets. – travis May 07 '09 at 14:39
  • 12
    I tweaked this code just a bit. I was able to shorten it to... ((bool)Eval("Active")) ? "Yes" : "No" Same idea though. Thanks. – Chuck Jul 15 '10 at 19:27
  • 6
    Thanks! I ended up with this for a databound nullable boolean in a repeater: <%# Eval("IsEmail") == DBNull.Value ? "No" : (bool)Eval("IsEmail") == false ? "No" : "Yes" %> – Aaron Anodide Feb 10 '11 at 02:32
  • I'd suggest voting for https://visualstudio.uservoice.com/forums/121579-visual-studio-2015/suggestions/2242024-add-a-iformattable-to-the-boolean-type to fix this, then DataStringFormat would work and you wouldn't have to use a item template – jmoreno Jan 13 '16 at 02:11
  • 1
    Shortened VB version: If(CBool(Eval("Active")), "Yes", "No") – Nugsson Sep 27 '21 at 14:58
16

Add a method to your page class like this:

public string YesNo(bool active) 
{
  return active ? "Yes" : "No";
}

And then in your TemplateField you Bind using this method:

<%# YesNo(Active) %>
Rune Grimstad
  • 35,612
  • 10
  • 61
  • 76
  • 5
    I think the template field binding should look like this: <%# YesNo((bool)Eval("Active")) %> – JasonS Aug 18 '10 at 22:13
7

Nope - but you could use a template column:

<script runat="server">
  TResult Eval<T, TResult>(string field, Func<T, TResult> converter) {
     object o = DataBinder.Eval(Container.DataItem, field);
     if (converter == null) {
        return (TResult)o;
     }
     return converter((T)o);
  }
</script>

<asp:TemplateField>
  <ItemTemplate>
     <%# Eval<bool, string>("Active", b => b ? "Yes" : "No") %>
  </ItemTemplate>
</asp:TemplateField>
Mark Brackett
  • 84,552
  • 17
  • 108
  • 152
6

You could use a Mixin.

/// <summary>
/// Adds "mixins" to the Boolean class.
/// </summary>
public static class BooleanMixins
{
    /// <summary>
    /// Converts the value of this instance to its equivalent string representation (either "Yes" or "No").
    /// </summary>
    /// <param name="boolean"></param>
    /// <returns>string</returns>
    public static string ToYesNoString(this Boolean boolean)
    {
        return boolean ? "Yes" : "No";
    }
}
Corey Coto
  • 198
  • 2
  • 10
  • 3
    Mixin? This is an example of an [extension method](http://msdn.microsoft.com/en-us/library/bb383977.aspx). – mason May 14 '14 at 20:40
3

Or you can use the ItemDataBound event in the code behind.

piet.t
  • 11,718
  • 21
  • 43
  • 52
Paco
  • 8,335
  • 3
  • 30
  • 41
3

I had the same need as the original poster, except that my client's db schema is a nullable bit (ie, allows for True/False/NULL). Here's some code I wrote to both display Yes/No and handle potential nulls.

Code-Behind:

public string ConvertNullableBoolToYesNo(object pBool)
{
    if (pBool != null)
    {
        return (bool)pBool ? "Yes" : "No";
    }
    else
    {
        return "No";
    }
}

Front-End:

<%# ConvertNullableBoolToYesNo(Eval("YOUR_FIELD"))%>
Shaun3180
  • 191
  • 2
  • 9
  • 1
    Downwote: You should never use Exceptions in normal programming logic. Instead try if(pBool.HasValue) return "No"; else return (bool)pBool ? "Yes":"No"; This assumes that your argument type is of bool?, which it should be. – Thomas Jespersen Dec 19 '10 at 09:35
  • @thomas-jespersen You are right - my initial example used some poor programming style so I fixed the code to test for a null value w/out the try/catch statement. I'd appreciate an up vote! – Shaun3180 Feb 16 '11 at 03:06
  • I agree with TJ above, but we're here to learn. Your code is just fine now, so upvote granted. :) – Michael Blackburn Apr 10 '11 at 23:41
  • 1
    Why not use public string `ConvertNullableBoolToYesNo(bool? pBool){ return (pBool.HasValue && pBool.Value) ? "Yes" : "No";}` – Trisped Dec 17 '12 at 20:20
  • The code still throws an InvalidCastException unless the parameter is a boolean, or can be cast to bool. Better change it to bool? like @ThomasJespersen said. – Tom Lint Dec 03 '14 at 08:31
1

This is how I've always done it:

<ItemTemplate>
  <%# Boolean.Parse(Eval("Active").ToString()) ? "Yes" : "No" %>
</ItemTemplate>

Hope that helps.

Chtioui Malek
  • 11,197
  • 1
  • 72
  • 69
0

This works:

Protected Sub grid_RowDataBound(sender As Object, e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles grid.RowDataBound
    If e.Row.RowType = DataControlRowType.DataRow Then
        If e.Row.Cells(3).Text = "True" Then
            e.Row.Cells(3).Text = "Si"
        Else
            e.Row.Cells(3).Text = "No"
        End If
    End If
End Sub

Where cells(3) is the column of the column that has the boolean field.

Cairnarvon
  • 25,981
  • 9
  • 51
  • 65
0

It's easy with Format()-Function

Format(aBoolean, "YES/NO")

Please find details here: https://msdn.microsoft.com/en-us/library/aa241719(v=vs.60).aspx