gridview显示正常,任何列的排序都很好。但是,当您单击链接按钮时,返回的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
中的数据视图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();
}
答案 0 :(得分:1)
当您通过GridView1_Sorting排序时,处理Page_Load然后处理GridView1_Sorting。因此数据显示正确。单击LinkButton时,将在GridView1__RowCommand之前处理Page_Load。通常,Gridview的DataBind位于Page_Load中,因此数据现在按原始顺序排列。要更正将排序也放在Page_Load DataBind中。
if(dt.Rows.Count&gt; 0)
{
DataView dv = new DataView(dt);
dv.Sort = ViewState["SortExpression"].ToString() + " " + ViewState["SortDirection"].ToString();
GridView1.DataSource = dv;
GridView1.DataBind();
}
我认为你不能对空的数据表进行排序。
您可以通过调试轻松验证这一点,并在Sorting和Page_Load中添加断点。
答案 1 :(得分:0)
我找到了解决方案。这对我有用。试试这个。
protected void LinkButton_Click(object sender, EventArgs e)
{
sortExpr = "Path";
GridView1_Sorting(null, null);
}
并改变这个:
string sortExpr;
protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
{
String sortExpression = null;
if (sortExpr == null)
{
sortExpression = e.SortExpression;
}
else
{
sortExpression = sortExpr;
}
Session["SortExpression"] = sortExpression;
if (Session["SortDirection"] != null && Session["SortDirection"].ToString() == SortDirection.Descending.ToString())
{
Session["SortDirection"] = SortDirection.Ascending;
SortGridview(sortExpression, "ASC");
}
else
{
Session["SortDirection"] = SortDirection.Descending;
SortGridview(sortExpression, "DESC");
}
}
private void SortGridview(string sortExpression, string Direction)
{
DataView dv = null;
DataTable dt = GridView1.DataSource as DataTable;
dv = new DataView(dt);
dv.Sort = sortExpression + " " + Direction;
GridView1.DataSource = dv;
GridView1.DataBind();
}