The gridview displays fine and sorting by either column works great. However when you click on the link button the CommandArgument that is returned is not the correct value. It is as if the CommandArgument is bound to the row and doesn't get sorted.
i.e. before sort
Text Command
abc A
aaa B
aab C
after sort
Text Command
aaa A
aab B
abc C
clicking on aaa would return "A" as the argument, not B like it should.
The GridView in an aspx file is defined like this:
<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>
It is bound to a dataview populated by a sql query and stored in the viewstate
ViewState["GridView1_DataSource"] = ds.Tables[0];
DataView dv = new DataView(ds.Tables[0]);
GridView1.DataSource = dv;
GridView1.DataBind();
My sorting method is
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();
}
When you sort via the GridView1_Sorting, Page_Load is processed then GridView1_Sorting. So the data is displayed correctly. When the LinkButton is clicked, the Page_Load is processed before the GridView1__RowCommand. Typically, a DataBind of the Gridview is in the Page_Load so the data is now in the original order. To correct put the sorting also in the Page_Load DataBind.
if (dt.Rows.Count > 0)
{
DataView dv = new DataView(dt);
dv.Sort = ViewState["SortExpression"].ToString() + " " + ViewState["SortDirection"].ToString();
GridView1.DataSource = dv;
GridView1.DataBind();
}
I do not think you can sort an empty datatable.
You can easily verify this by Debugging and added a breakpoint in Sorting and Page_Load.