c# - Asp.net grdiview : can i format the dataitems in an itemtemplate?

标签 c# asp.net gridview formatting

我在 gridview 的项目模板中有这段代码:

<%# DataBinder.Eval (Container.DataItem, "DiscountAmount")%>

这是一个十进制值,显示 20.300000000000,这在技术上是正确的,但我更愿意显示 20.30 或 20,30,具体取决于文化。

但我从来都不是 gridviews 的忠实粉丝,而且 DataBinder.EvalContainer.DataItem 也不是好 friend ,而我迷失了如何使用它。

它有一个特殊的前缀 (<%#),当我输入原始代码以外的任何内容时,它是不好的,但是将 <%# 更改为 <%= 或 <% 似乎也不起作用?

最佳答案

这也行:

<%#= String.Format("{0, 0:N2}",DataBinder.Eval (Container.DataItem, "DiscountAmount"))%>

编辑:我和您一样对声明式数据绑定(bind)语法感到不适。 您可以通过调用 RowDataBound 在代码隐藏中完成同样的事情事件并实现您想要进行的任何更改,因为数据已绑定(bind)到 GridViewRow .

为此,您需要通过设置 OnRowDataBound 在标记中连接事件到您的事件处理程序的名称,如下所示:

<asp:GridView ID="InvoiceGrid" OnRowDataBound="InvoiceGrid_RowDataBound".....>

然后您使用如下签名在代码隐藏中创建一个事件处理程序:

protected void InvoiceGrid_RowDataBound(object sender, GridViewRowEventArgs e)

您在该事件处理程序中做的第一件事是测试哪种类型的 GridViewRow输入它是:

if (e.Row.RowType == DataControlRowType.DataRow)....

然后你做任何你想做的格式化。

对于喜欢声明式标记的人来说,这可能看起来很麻烦。但是对于喜欢编写代码的人来说,您可以在代码隐藏中做更多的事情。

关于c# - Asp.net grdiview : can i format the dataitems in an itemtemplate?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4461174/

相关文章:

c# - MVVM基金会: Why return ICommand when its defined as RelayCommand

c# - 在一个组合框中显示数据库中的多列

c# - 从不同的方法访问数据表

c# - 带有每个项目的详细信息行的 Gridview

android - 具有自适应宽度/高度的android中带有方形项目的GridView

c# - 更新 Controller 中的模型?

c# - 如何在 ADO.NET 对象上调用 Dispose?

c# - 启动 Internet Explorer 进行调试

asp.net - 如何在 ASP.NET 中使用 Crystal Reports?

wpf - 更改 GridView 列标题的字体大小