Can I convert a boolean to Yes/No in a ASP.NET GridView

前端 未结 9 1235
孤街浪徒
孤街浪徒 2020-12-22 17:17

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

相关标签:
9条回答
  • 2020-12-22 17:24

    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>
    
    0 讨论(0)
  • 2020-12-22 17:25

    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";
        }
    }
    
    0 讨论(0)
  • 2020-12-22 17:27

    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.

    0 讨论(0)
  • 2020-12-22 17:34

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

    0 讨论(0)
  • 2020-12-22 17:34

    This is how I've always done it:

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

    Hope that helps.

    0 讨论(0)
  • 2020-12-22 17:39

    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>
    
    0 讨论(0)
提交回复
热议问题