Why is my Datagrid Sort not working?

A

anonieko

This applies to ASPNET 1.1 and it took me a bit of time figuring
out cause of the problem
---------------------------

I enabled sorting. I have a method that
handles the SortCommand and it fires ok.

After getting the view and assigning the field "Sort"
of the dataview with the correct expression,
the datagrid still doesn't sort.


Well, here is one reason. Look the the HTML of the datagrid.

If the "DataSource" attribute is defined, then you have to
remove it. For example, the following has the attribute "DataSource"
define.

<asp:datagrid id=TransactionsDataGrid runat="server"
AllowSorting="True" AutoGenerateColumns="False" AllowPaging="True"
CellPadding="2" BackColor="White" BorderWidth="1px" BorderStyle="None"
BorderColor="#3366CC" Width="100%" ShowFooter="True" DataSource="<%#
transactionsDataSet %>">


After removing that attribute, try to see if it would now work:

Here are some snippets: (for reference)
=========================================

private void DataGrid1_SortCommand(object source,
System.Web.UI.WebControls.DataGridSortCommandEventArgs e)
{
Session["PrevSort"] = Session["Sort"];
Session["Sort"] = (string) e.SortExpression;

// Logic to reverse the sort when same link is clicked again.
string prevSort = (string) Session["PrevSort"];
string currSort = (string) Session["Sort"];

if ( prevSort.Replace("DESC", "").Trim() ==
currSort.Replace("DESC", "").Trim() )
{
if ( prevSort.EndsWith("DESC") )
currSort.Replace("DESC", "");
else
currSort += " DESC";
}
Session["Sort"] = currSort;

BindGrid();
}



private DataView CreateDataSource()
{
sqlConnection1.ConnectionString = GetConnectionString();
sqlDataAdapter1.Fill(this.transactionsDataSet);
DataView dv = transactionsDataSet.Tables[0].DefaultView;
string sortKey = (string) Session["Sort"];


dv.Sort = sortKey;
return dv;
}

private void BindGrid()
{
// Assign datasource only here. Remove any assignment to
attribute 'DataSource' in the HTML
TransactionsDataGrid.DataSource = CreateDataSource();

// This will attemp to Bind. If pageindex is out of synch, it
resets to first page.
try
{
TransactionsDataGrid.DataBind();
}
catch( HttpException exc)
{
if ( exc.Message.StartsWith("Invalid CurrentPageIndex
value") )
{
TransactionsDataGrid.CurrentPageIndex = 0;
TransactionsDataGrid.DataBind();
}
}
}


private void DataGrid1_PageIndexChanged(object source,
System.Web.UI.WebControls.DataGridPageChangedEventArgs e)
{
TransactionsDataGrid.CurrentPageIndex = e.NewPageIndex;
BindGrid();
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,995
Messages
2,570,230
Members
46,819
Latest member
masterdaster

Latest Threads

Top