我正在构建一个小型webapp来跟踪赢/输/平均值。数据保存在XML文件中(因为它只有几行)。我想尝试给页面的访问者,按每个列排序的能力(播放,赢取,平均)。我能够对它进行排序Played和Won,但不是Average,因为Average是一个计算值。
如何对GetWinAverage函数的结果进行排序?
目前的情况如下:
<asp:GridView ID="Results" runat="server" AutoGenerateColumns="false" AllowSorting="true" OnSorting="gvResults_Sorting" EnableViewState="true">
<Columns>
<asp:TemplateField HeaderText="Played" SortExpression="Played">
<ItemTemplate>
<asp:Label ID="lblPlayed" runat="server" Text='<%# Eval("Played") %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
<Columns>
<asp:TemplateField HeaderText="Won" SortExpression="Won">
<ItemTemplate>
<asp:Label ID="lblWon" runat="server" Text='<%# Eval("Won") %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
<Columns>
<asp:TemplateField HeaderText="Average" SortExpression="Average">
<ItemTemplate>
<asp:Label ID="lblAverage" runat="server" Text='<%# GetWinAverage(Eval("Won"), Eval("Played")) %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
GetWinAverage的位置如下:
public string GetWinAverage(object gamesWon, object gamesPlayed)
{
string strReturn = "";
double iWon = Convert.ToDouble(gamesWon);
double iPlayed = Convert.ToDouble(gamesPlayed);
if (iPlayed < 0)
{
return "0%";
}
else
{
double dReturn = (iWon / iPlayed) * 100;
strReturn = string.Format("{0:N2}%", dReturn);
return strReturn;
}
}
排序看起来像这样:
private const string ASCENDING = " ASC";
private const string DESCENDING = " DESC";
public SortDirection GridViewSortDirection
{
get
{
if (ViewState["sortDirection"] == null)
ViewState["sortDirection"] = SortDirection.Ascending;
return (SortDirection)ViewState["sortDirection"];
}
set { ViewState["sortDirection"] = value; }
}
protected void gvResults_Sorting(object sender, GridViewSortEventArgs e)
{
string sortExpression = e.SortExpression;
if (GridViewSortDirection == SortDirection.Ascending)
{
GridViewSortDirection = SortDirection.Descending;
SortGridView(sortExpression, DESCENDING);
}
else
{
GridViewSortDirection = SortDirection.Ascending;
SortGridView(sortExpression, ASCENDING);
}
}
private void SortGridView(string sortExpression, string direction)
{
// You can cache the DataTable for improving performance
DataTable dt = dtPlayers;
DataView dv = new DataView(dt);
dv.Sort = sortExpression + direction;
gvResults.DataSource = dv;
gvResults.DataBind();
}
答案 0 :(得分:1)
最简单的方法可能是修改DataTable以使用计算数据列。
您可以通过添加“平均值”列并将DataColumn.Expression属性设置为Won/Played * 100
来执行此操作。然后像任何其他列一样绑定到它。