The part 1 example has slight limitation on the programmer side who wants to use the code above as is. The limitation is he/she has to remember to set the sortexpression property of column in datagrid as database field name followed by sort direction at design time e.g. lastname ASC.
The following example illustrates the use of adding sortexpression and sortdirection dynamic attributes to datagrid, maintain their state through view state and sort data in datagrid using dataview. The sortexpression property of datagrid set in this example is to generate sortcommand event only. The sortexpression attribute of datagrid stores last column name used for sorting and sortdirection attribute stores last direction used for sorting.
Design Time:
- Drag and drop a DatGrid on the form.
- Set AllowSorting property of the grid to True.
- Set AutogenerateColumns property of the grid to False.
- Add bound columns to datagrid and set their properties as follows. The sortexpression property refers to the name of column in database table.
Note: Employees table from Northwind database is being used to illustrate the purpose.
DataTextField |
Header Text |
Sort Expression |
EmployeeID |
Employee ID |
EmployeeID |
LastName |
Last Name |
LastName |
FirstName |
First Name |
FirstName |
Title |
Title |
Title |
City |
City |
City |
Country |
Country |
Country |