Live Chat Icon For mobile
Live Chat Icon

How to do Bidirectional Sorting in the DataGrid

Platform: ASP.NET| Category: DataGrid

<asp:DataGrid id='DataGrid1' OnSortCommand ='SortDataGrid' runat='server' AllowSorting='True' EnableViewState='False'></asp:DataGrid>

VB.NET


Protected SQLStmt As String = 'Select * from Products  '
Dim myconnection As SqlConnection
Dim myda As SqlDataAdapter
Dim ds As DataSet
Dim strConn As String
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
	binddata()
End Sub

Sub binddata()
	strConn = 'Server=localhost;uid=sa;password=;database=northwind;'
        	myconnection = New SqlConnection(strConn)
        	myda = New SqlDataAdapter(SQLStmt, myconnection)
        	ds = New DataSet
        	myda.Fill(ds, 'AllTables')
        	DataGrid1.DataSource = ds
        	DataGrid1.DataBind()
End Sub

Protected Sub SortDataGrid(ByVal source As Object, ByVal e As System.Web.UI.WebControls.DataGridSortCommandEventArgs)
        	If ViewState('SortOrder') Is Nothing Then
            		ViewState('SortOrder') = ' ASC'
        	ElseIf ViewState('SortOrder') = ' ASC' Then
            		ViewState('SortOrder') = ' DESC'
        	Else
            		ViewState('SortOrder') = ' ASC'
        	End If
        	SQLStmt = SQLStmt & ' ORDER BY ' & e.SortExpression & ' ' & ViewState('SortOrder')
	binddata()
End Sub

C#


SqlConnection myconnection ; 
SqlDataAdapter myda ; 
DataSet ds ; 
String strConn ;
string SQLStmt= 'Select * from Products  ';
private void Page_Load(object sender, System.EventArgs e)
{
	// Put user code to initialize the page here
	binddata();
}

void binddata()
{
	strConn = 'Server=localhost;uid=sa;password=;database=northwind;';
	myconnection =new SqlConnection(strConn);
	myda = new SqlDataAdapter(SQLStmt, myconnection);
	ds = new DataSet();
	myda.Fill(ds, 'AllTables');
	DataGrid1.DataSource = ds;
	DataGrid1.DataBind();
}

protected void SortDataGrid(object source   , System.Web.UI.WebControls.DataGridSortCommandEventArgs   e  )  
{
	if (ViewState['SortOrder'] ==null)
	{
		ViewState['SortOrder'] = ' ASC';
	}
	else if (ViewState['SortOrder'].ToString () == ' ASC' )
	{
		ViewState['SortOrder'] = ' DESC';
	}
	else
	{
		ViewState['SortOrder'] = ' ASC';
	}
	SQLStmt = SQLStmt + ' ORDER BY ' + e.SortExpression.ToString () + ' ' + ViewState['SortOrder'];
	binddata();
}

Share with

Share on twitter
Share on facebook
Share on linkedin