Scenario:
1. columns in the DataGrid are automatically generated.
2. The DataGrid supports sorting.
Requirement: When you click the column header of a column, the column is sorted based on the corresponding fields. Add the "up/down" arrow behind the field in ascending/descending order.
The DataGrid. columns set is empty because columns are automatically generated. The headertext of Columns cannot be traversed.
You can set the content in the cell when binding the row and column headers in databound.
Private Void Dgmain_itemdatabound ( Object Sender, system. Web. UI. webcontrols. datagriditemeventargs E)
{
//
If (E. Item. itemtype = Listitemtype. header)
{
For ( Int I = 0 ; I < E. Item. cells. Count; I ++ )
{
E. Item. cells [I]. Attributes. Add ( " Class " , " Gridhead " );
Up and down arrows of sorting # Region Up and down arrows of sorting
Try
{
If (I > 0 ) // Do not process columns 0th
{
Linkbutton lbheader = (Linkbutton) E. Item. cells [I]. controls [ 0 ];
String Currentcolumnname = Lbheader. text;
String Sortexpression = String . Empty;
String Sortdirection = String . Empty;
If (Dgmain. attributes [ " Sortexpression " ] ! = Null )
Sortexpression = Dgmain. attributes [ " Sortexpression " ]. Tostring ();
If (Dgmain. attributes [ " Sortdirection " ] ! = Null )
Sortdirection = Dgmain. attributes [ " Sortdirection " ]. Tostring ();
If (Sortexpression = Currentcolumnname)
{
If (Sortdirection = " Desc " )
{< br> lbheader. text = currentcolumnname + " margin " ;
}
Else
{< br> lbheader. text = currentcolumnname + " margin " ;
}
}
}
}
Catch
{}
# Endregion
}
}
Note:
The content in the column header cell in the sortable column is of the linkbutton type. E. Item. cells [0]. text cannot be used for such column headers.
In addition, in page_load or other places on the page, the normal content of the DataGrid is obtained using DataGrid. items, that is, the row content, excluding the header and footer.