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>

VB.NET


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
            BindDataGrid('ProductId')
        End If
End Sub

Protected Sub SortData(ByVal source As Object, ByVal e As System.Web.UI.WebControls.DataGridSortCommandEventArgs)
        BindDataGrid(e.SortExpression.ToString())
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
        DataGrid1.DataBind()
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

C#


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

protected void SortData(Object source,  System.Web.UI.WebControls.DataGridSortCommandEventArgs  e )
{
	BindDataGrid(e.SortExpression.ToString());
}

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

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.