使用数据绑定控件从数据绑定Gridview中相关实体的列中获取总和
我有一个在页面加载时绑定到数据源的网格视图。数据源连接到各种其他数据库表,即。 datasourceItem.latedEntity
gridview中有一个列,其值取决于所有相关latedEntities
中某个字段的总和。
因此,dataSourceItem
与latedEntity
具有一对多关系,我需要对所有相关latedEntities
中特定列的值进行求和。我想尽可能简单地做到这一点,并且我知道这种语法是错误的,但这正是我想要做的:
标记:
<asp:TemplateField HeaderText="Sum">
<ItemTemplate>
<asp:Label ID="lblSum" runat="server" Text='<%# Bind("relatedEntity.ColumnName").Sum() %>' />
</ItemTemplate>
</asp:TemplateField>
代码隐藏(数据绑定):
myGridview.DataSource = from ds in DataContext.dataSource
where ds.Id == selectId
select ds;
myGridview.DataBind();
我想将代码量保持在最低限度,所以如果这可能的话,请帮我弄清楚如何做。需要明确的是,我想要执行的代码行是这样的:
'<%# Bind("relatedEntity.ColumnName").Sum() %>'
或者至少是达到这种效果的代码。我不一定必须使用 Sum()
方法...如果有不同/更好的方法来处理这个问题,请随时告诉我
I have a gridview that is bound to a datasoure on page load. The datasource is connected to various other database tables, ie. datasourceItem.relatedEntity
There is a column in the gridview whose value is dependent upon the sum of a certain field in all related relatedEntities
.
So dataSourceItem
has a one to many relationship with relatedEntity
, and I need to sum the value from a specific column in all related relatedEntities
. I want to do this as simply as possible, and I know this syntax is wrong, but this is kind of what I wanted to do:
Markup:
<asp:TemplateField HeaderText="Sum">
<ItemTemplate>
<asp:Label ID="lblSum" runat="server" Text='<%# Bind("relatedEntity.ColumnName").Sum() %>' />
</ItemTemplate>
</asp:TemplateField>
Code-behind (databinding):
myGridview.DataSource = from ds in DataContext.dataSource
where ds.Id == selectId
select ds;
myGridview.DataBind();
I want to keep the amount of code to a minimum, so if this is at all possible, please help me figure out how. To be clear, the line of code I want to make work is this:
'<%# Bind("relatedEntity.ColumnName").Sum() %>'
Or at least something to that effect. I don't necessarily have to use the Sum()
method... if there is a different/better way of handling this, feel free to let me know
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
首先您需要使用 Eval 而不是 Bind。
接下来,您需要将计算的表达式转换为 EntityCollection 类型
此外,您还需要正确的导入
<%@ Import Namespace="YourEntitiesNamespace" %>
和 System.Data.Entity
编辑:
如果页面无法编译,则需要在 web.config 中进行设置。
您还可以使用 import 指令去掉类型的全名
First you need to use Eval instead of Bind.
Next, you need to cast the evaluated expression to your EntityCollection type
Also you need to the proper imports
<%@ Import Namespace="YourEntitiesNamespace" %>
and System.Data.Entity
Edit:
If the page is doesn't compile, this is needed in web.config
Also you can get rid off the full name of the type using the import directive