I’m working on a ListView and am getting that feeling that I’m doing something fundamentally wrong when it comes to implementing sorting. Rather than being able to depend on the values of List1.SortExpression and List1.SortDirection, I’m resorting to hidden fields because List1.SortExpression is always blank and List1.SortDirection is always SortDirection.Ascending.
On my .aspx page: (edited out irrelevant code)
<asp:HiddenField runat="server" ID="hdnSortExpression" />
<asp:HiddenField runat="server" ID="hdnSortDirection" />
<asp:ListView runat="server" ID="List1"
OnItemCommand="List1_ItemCommand"
OnSorting="List1_Sorting">
<LayoutTemplate>
<table border="0" cellpadding="1">
<thead>
<tr>
<th><asp:LinkButton runat="server" ID="BtnCompanyCode" CommandName="Sort" CommandArgument="CompanyCode" Text="Company Code" /></th>
... more columns ...
</tr>
</thead>
<tbody>
<tr runat="server" id="itemPlaceholder"></tr>
</tbody>
</table>
</LayoutTemplate>
In my Code Behind:
protected void List1_ItemCommand(object sender, ListViewCommandEventArgs e)
{
// empty for now
}
protected void List1_Sorting(object sender, ListViewSortEventArgs e)
{
SortDirection sortDirection;
String sortExpression = e.SortExpression; // how we need to do it in Sorting
if (hdnSortExpression.Value.ToLower() == sortExpression.ToLower())
sortDirection = hdnSortDirection.Value == SortDirection.Ascending.ToString() ? SortDirection.Descending : SortDirection.Ascending;
else
sortDirection = SortDirection.Ascending;
DoSortList(sortExpression, sortDirection); // this sets column headings' sort indicator arrows
List1_BindData(sortExpression, sortDirection); // sets DataSource and calls DataBind()
// the hacky part: setting hidden fields to store sortExpression and sortDirection
hdnEligibilitySortExpression.Value = sortExpression;
hdnEligibilitySortDirection.Value = sortDirection.ToString();
}
private void List1_BindData(String sortExpression, SortDirection sortDirection)
{
List<SomeEntity> list = null;
list = SomeEntity.GetBySsn(_ssn).ToList(); // methods generated by an ORM pointing to an Oracle database
switch (sortExpression.ToLower())
{
case "CompanyCode":
if (sortDirection == SortDirection.Ascending)
List1.DataSource = list.OrderBy(o => o.CompanyCode);
else
List1.DataSource = list.OrderByDescending(o => o.CompanyCode);
break;
... other cases ...
}
List1.DataBind();
}
It works — each column gets sorted correctly, clicking the same column reverses sort direction, but I have to conclude that I’ve wired things up incorrectly because I cannot depend on the SortDirection and SortExpression properties. What am I doing wrong?
Take a look at this MSDN example.
You will notice that the DataSource is a SqlDataSource. This is one of the DataSource types that .Net understands how to sort. Others, not so much.
Here’s another MSDN article that specifies the DataSource types: