![]() |
Web Development »
ASP.NET Controls »
General
Intermediate
Two way sorting in DataGrid using Bound ColumnsBy azamsharpTwo way sorting in DataGrid using bound columns. |
C#, Windows, .NET, ASP.NET, Visual Studio, Dev
|
|
Advanced Search Add to IE Search |
|
|
|
||||||||||||||||
In this small code snippet, I will show how to perform two way sorting in DataGrid using bound columns. Remember, there can be numerous ways you can sort the items in the DataGrid and this is just one of them.
First, add some columns in your DataGrid using Property Builder. Since this is an intermediate level article, you should know how to perform this. Once you add the bound columns, give the DataGrid a data source and populate it with some data.
Okay, up till now, the DataGrid should be populated with some data. Now in the Properties window of the DataGrid, set AllowSorting = "true". Okay, now sorting is enabled and all you need now is the actual code that sorts the DataGrid.
Whenever the Columns header is clicked, SortCommand event is fired. So, place the code below in the SortCommand event handler:
private void Sort_DataGrid(object source,
System.Web.UI.WebControls.DataGridSortCommandEventArgs e)
{
// Never use Queries like this always use Stored procedures
SqlCommand myCommand = new SqlCommand("SELECT * FROM Categories",
myConnection);
myCommand.CommandType = CommandType.Text;
SqlDataAdapter myAdapter = new SqlDataAdapter(myCommand);
DataSet ds = new DataSet();
myAdapter.Fill(ds,"Categories");
DataView dv = new DataView(ds.Tables["Categories"]);
if( (numberDiv%2) == 0 )
dv.Sort = e.SortExpression + " " + "ASC";
else
dv.Sort = e.SortExpression + " " + "DESC";
numberDiv++;
myDataGrid.DataSource = dv;
myDataGrid.DataBind();
}
In the above code, "numberDiv" is the public static Int32 variable which keeps count of the even and odd number of mouse clicks on the header. The heart of this example is the DataView object which has a SortExpression property, it represents the name of the column clicked.
And lastly, just assign the DataSource to the DataView and bind the grid on the page.
| You must Sign In to use this message board. | ||||||||||||||||||||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||||||||||||||||||||
General
News
Question
Answer
Joke
Rant
Admin
|
PermaLink |
Privacy |
Terms of Use
Last Updated: 19 Aug 2004 Editor: Smitha Vijayan |
Copyright 2004 by azamsharp Everything else Copyright © CodeProject, 1999-2009 Web17 | Advertise on the Code Project |