Live Chat Icon For mobile
Live Chat Icon

How to highlight the Column that is sorted in a DataGrid

Platform: ASP.NET| Category: DataGrid

<asp:DataGrid id='DataGrid1' OnItemDataBound ='ItemDB' AllowSorting='True' OnSortCommand='SortData' runat='server'></asp:DataGrid>


Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        ’Put user code to initialize the page here
        If Not Page.IsPostBack Then
        End If
End Sub

Protected Sub SortData(ByVal source As Object, ByVal e As System.Web.UI.WebControls.DataGridSortCommandEventArgs)
End Sub

Sub BindDataGrid(ByVal sortfield As String)
        ViewState('SortExpression') = sortfield
        ’Fill the DataSet
        Dim dv As DataView = ds.Tables(0).DefaultView
        dv.Sort = sortfield
        DataGrid1.DataSource = dv
End Sub

Protected Sub ItemDB(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DataGridItemEventArgs)
        Dim dv As DataView = DataGrid1.DataSource
        Dim dc As DataColumnCollection = dv.Table.Columns
        If e.Item.ItemType = ListItemType.Header Then
            If ViewState('SortExpression') <> '' Then
                e.Item.Cells(dc.IndexOf(dc(ViewState('SortExpression')))).BackColor = Color.BlueViolet
                e.Item.Cells(dc.IndexOf(dc(ViewState('SortExpression')))).ForeColor = Color.AntiqueWhite
            End If
        End If
End Sub


private void Page_Load(object sender, System.EventArgs e)
	// Put user code to initialize the page here
	if(! Page.IsPostBack  )

protected void SortData(Object source,  System.Web.UI.WebControls.DataGridSortCommandEventArgs  e )

void BindDataGrid(string sortfield)
	ViewState['SortExpression'] = sortfield;
	//Fill the dataset
	DataView dv    = ds.Tables[0].DefaultView;
	dv.Sort = sortfield;
	DataGrid1.DataSource = dv;

protected void ItemDB(object sender   ,System.Web.UI.WebControls.DataGridItemEventArgs  e   )  
	DataView dv    =(DataView) DataGrid1.DataSource;
	DataColumnCollection dc    = dv.Table.Columns;
	if (e.Item.ItemType == ListItemType.Header ) 
		if (ViewState['SortExpression'].ToString()!= '')
			e.Item.Cells[dc.IndexOf( dc[ViewState['SortExpression'].ToString ()])].BackColor = Color.BlueViolet;
			e.Item.Cells[dc.IndexOf(dc[ViewState['SortExpression'].ToString ()])].ForeColor = Color.AntiqueWhite;

Share with

Related FAQs

Couldn't find the FAQs you're looking for?

Please submit your question and answer.