VB.NET - Sort DataGridView - Asked By Divyesh Mistry on 06-Aug-10 12:20 AM

Respected Sir

How to sort datagridview data using vb.net source code?

ans plz.
shital patil replied to Divyesh Mistry on 06-Aug-10 12:38 AM

hi,
use this code
DGV.Sort(DGV.Columns(0), System.ComponentModel.ListSortDirection.Ascending)
'Where DGV is a DataGridView
sri sri replied to Divyesh Mistry on 06-Aug-10 12:48 AM
hi,

check the below code

 <asp:GridView ID="TaskGridView" runat="server"
      AllowSorting="true"
      OnSorting="TaskGridView_Sorting" >
    </asp:GridView>



Protected Sub TaskGridView_Sorting(ByVal sender As Object, ByVal e As GridViewSortEventArgs)

    'Retrieve the table from the session object.
    Dim dt = TryCast(Session("TaskTable"), DataTable)

    If dt IsNot Nothing Then

    'Sort the data.
    dt.DefaultView.Sort = e.SortExpression & " " & GetSortDirection(e.SortExpression)
    TaskGridView.DataSource = Session("TaskTable")
    TaskGridView.DataBind()

    End If

  End Sub

for more info check the below link
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview.sorting.aspx
Anand Malli replied to Divyesh Mistry on 06-Aug-10 01:38 AM
Hi Divyesh

Consider following code,first i am showing the mark up where event is registered and the other is .vb file right

<asp:GridView runat="server" AutoGenerateColumns="false" AllowSorting="true"
      ID="grdSortTest" >
  <Columns>
 <asp:BoundField DataField="empName" HeaderText="Name" SortExpression="empName"/>
    <asp:BoundField DataField="empSalary" HeaderText="Salary"  SortExpression="empSalary"/>
  </Columns>
</asp:GridView>

here i have taken two columns of emp table and we will try to sort them,we have made AlloSorting="True",so the column name is gridview header would be hyperlinked,so that we can click them,now lets see the code behind
Imports System.Data.SqlClient
Imports System.Data
Partial Class Employee Inherits System.Web.UI.Page
  
Private Property SortDirection() As String
  Get
   If (ViewState("SortDirection") Is Nothing) Then ViewState("SortDirection") = String.Empty
      Return ViewState("SortDirection").ToString()
    End Get
    Set(ByVal value As String)
      ViewState("SortDirection") = value
    End Set
  End Property
  Protected Sub form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles form1.Load
    If (Not IsPostBack) Then
      grdSortTest.DataSource = GetSortedData(String.Empty)
      grdSortTest.DataBind()
    End If
  End Sub
  Private ReadOnly Property ConnectionString() As String
    Get
      Return "<your connection string>"
    End Get
  End Property
  Private ReadOnly Property Connection() As SqlConnection
    Get
      Dim Con As New SqlConnection(ConnectionString)
      Con.Open()
      Return Con
    End Get
  End Property
  Public Function GetSortedData(ByVal Expression As String) As DataView
    Dim strQuery= "select * from emp"
    Dim SampleSource As New DataSet
    Dim SortableView As DataView
    Try
      Dim SampleDataAdapter As New SqlDataAdapter(strQuery, ConnectionString)
      SampleDataAdapter.Fill(SampleSource)
      SortableView = SampleSource.Tables(0).DefaultView
      If (Not String.IsNullOrEmpty(Expression)) Then
        If (SortDirection.ToUpper() = "ASC") Then
          SortDirection = "DESC"
        Else
          SortDirection = "ASC"
        End If
        SortableView.Sort = Expression & " " & SortDirection
      End If
    Catch ex As Exception
      Throw ex
    End Try
    Return SortableView
  End Function
  Protected Sub grdSortTest_Sorting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewSortEventArgs) Handles GridView1.Sorting
    grdSortTest.DataSource = GetSortedData(e.SortExpression)
    grdSortTest.DataBind()
  End Sub
End Class

Here the code is self explaintory,so when you click on any of the column header,what it will do is it will call...grdiviews sorting method and from that we are making sorted datasource,so if sort we are clicking for the first time thee will not be any viewstate information for sorting,so we will set ViewState and then onwards we will be able to get the value from ViewState and set the sorting expression opposite to Viewstate as if its Asc we will make it Desc

let me know
thxs
Anoop S replied to Divyesh Mistry on 06-Aug-10 01:39 AM
When you bind your DataGridView to your datasource, use a bindingsource.

Dim nwData as CustomersDataSet = CustomersDataSet.GetCustomers()
m_CustomersGrid.DataSource = m_CustomersBindingSource
m_CustomersBindingSource.DataSource = nwData.Customers

Then you can sort using the BindingSource.

CustomersBindingSource.Sort = "ContactName ASC"

And you can find using the BindingSource.

Dim index as integer = _
CustomersBindingSource.Find("CompanyName", CompanyNameTextBox.Text)
If index <-1 then 'it was found; move to that position
CustomersBindingSource.Position = index
End If