我有一个ASP.NET GridView
,其列映射到布尔值。我想显示“是”/“否”而不是“真”/“假”。其实我想要“Ja”/“Nej”(丹麦文)。
这可能吗?
<asp:gridview id="GridView1" runat="server" autogeneratecolumns="false">
<columns>
...
<asp:boundfield headertext="Active" datafield="Active" dataformatstring="{0:Yes/No}" />
...
</columns>
</asp:gridview>
答案 0 :(得分:126)
我将此代码用于VB:
<asp:TemplateField HeaderText="Active" SortExpression="Active">
<ItemTemplate><%#IIf(Boolean.Parse(Eval("Active").ToString()), "Yes", "No")%></ItemTemplate>
</asp:TemplateField>
这适用于C#(未经测试):
<asp:TemplateField HeaderText="Active" SortExpression="Active">
<ItemTemplate><%# (Boolean.Parse(Eval("Active").ToString())) ? "Yes" : "No" %></ItemTemplate>
</asp:TemplateField>
答案 1 :(得分:14)
向您的网页类添加一个方法,如下所示:
public string YesNo(bool active)
{
return active ? "Yes" : "No";
}
然后使用此方法在TemplateField
你Bind
中:
<%# YesNo(Active) %>
答案 2 :(得分:7)
不 - 但你可以使用模板栏:
<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>
答案 3 :(得分:6)
你可以使用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";
}
}
答案 4 :(得分:3)
或者您可以在后面的代码中使用ItemDataBound
事件。
答案 5 :(得分:2)
我有与原始海报相同的需求,除了我的客户端的db模式是可以为空的位(即允许True / False / NULL)。这里写的一些代码都显示是/否并处理潜在的空值。
<强>代码隐藏:强>
public string ConvertNullableBoolToYesNo(object pBool)
{
if (pBool != null)
{
return (bool)pBool ? "Yes" : "No";
}
else
{
return "No";
}
}
<强>前端强>
<%# ConvertNullableBoolToYesNo(Eval("YOUR_FIELD"))%>
答案 6 :(得分:1)
这就是我一直以来的做法:
<ItemTemplate>
<%# Boolean.Parse(Eval("Active").ToString()) ? "Yes" : "No" %>
</ItemTemplate>
希望有所帮助。
答案 7 :(得分:0)
这有效:
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
其中cells(3)
是具有布尔字段的列的列。
答案 8 :(得分:0)
使用Format() - 函数
很容易Format(aBoolean, "YES/NO")
请在此处查找详细信息: https://msdn.microsoft.com/en-us/library/aa241719(v=vs.60).aspx