views:

7988

answers:

5

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>
+4  A: 

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
+3  A: 

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

Paco
It will be helpful to him if you can write an example snippet.
icelava
+10  A: 

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
the c# code works nicely, I've just used it :)
pomarc
Thanks! ☺ I actually marked this question as a fave so that I can reference (eg copy/paste) those snippets.
travis
I tweaked this code just a bit. I was able to shorten it to...((bool)Eval("Active")) ? "Yes" : "No"Same idea though. Thanks.
Chuck
+6  A: 

Add a method to your page class like this:

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

And then in your tempate field you bind using this method:

<%# YesNo(Active) %>
Rune Grimstad
I think the template field binding should look like this: <%# YesNo((bool)Eval("Active")) %>
JasonS
+3  A: 

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