网格视图显示正常,并且按任一列排序都很好。但是,当您单击链接按钮时,返回的 CommandArgument 不是正确的值。就好像 CommandArgument 绑定到行并且没有被排序。
即排序前
Text Command
abc A
aaa B
aab C
排序后
Text Command
aaa A
aab B
abc C
单击 aaa 将返回“A”作为参数,而不是应该返回的 B。
aspx 文件中的 GridView 定义如下:
<asp:GridView ID="GridView1" runat="server"
AllowSorting="True"
AutoGenerateColumns="False"
EmptyDataText="No Results to Display"
GridLines="None"
onsorting="GridView1_Sorting" >
<Columns>
<asp:TemplateField HeaderText="File Name" SortExpression="Path">
<ItemTemplate>
<asp:LinkButton ID="linkbutton1" runat="server" Text='<%# Eval("Title") %>' OnCommand="LinkButton_Click" CommandArgument='<%# Bind("Path") %>' ></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField HeaderText="Document Type" DataField="DocumentCategory (Text)" SortExpression="DocumentCategory (Text)" />
</Columns>
</asp:GridView>
它绑定到由 sql 查询填充的数据视图并存储在视图状态中
ViewState["GridView1_DataSource"] = ds.Tables[0];
DataView dv = new DataView(ds.Tables[0]);
GridView1.DataSource = dv;
GridView1.DataBind();
我的排序方法是
protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
{
string sortDir = "ASC";
if (ViewState["SortDirection"] == null)
ViewState["SortDirection"] = "ASC";
if (ViewState["SortDirection"].ToString() == "ASC")
{
sortDir = "DESC";
ViewState["SortDirection"] = "DESC";
}
else
{
ViewState["SortDirection"] = "ASC";
}
DataTable dt = (DataTable)ViewState["GridView1_DataSource"];
DataView dv = new DataView(dt);
dv.Sort = e.SortExpression + " " + sortDir;
GridView1.DataSource = dv;
GridView1.DataBind();
}