Click here to Skip to main content
15,888,113 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello All,

I want to implemented sorting in gridview in window application in c#.

Thanks
Posted

hi try this
For GridView paging and sorting write the following code in source file of aspx webpage:
VB
<asp:GridView
              ID="grdCause"
              runat="server
              EnableSortingAndPagingCallback="True"
              AllowPaging="True"
              AllowSorting="True"
              onpageindexchanging="grdCause_PageIndexChanging"
              onsorting="grdCause_Sorting"
         >
</asp:GridView>


The following method is for Loading the Gridview .In this method am taking dataset and bind that dataset to Gridview.
ExecuteProcedure is the method in my sqlhelper class.For that method Click here.
C#
private void LoadGrid()
    {

        DataSet ds = dal.ExecuteProcudere("CauseSelectAll", ht);
        grdCause.DataSource = ds.Tables[0];
        grdCause.DataBind();
    }

Gridview pageindexChanging Event  for paging:
protected void grdCause_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        grdCause.PageIndex = e.NewPageIndex;
        LoadGrid();
    }

Gridview Sorting  Event  for Sorting:

    protected void grdCause_Sorting(object sender, GridViewSortEventArgs e)
    {
        string sortExpression = e.SortExpression;

        if (GridViewSortDirection == SortDirection.Ascending)
        {
            GridViewSortDirection = SortDirection.Descending;
            SortGridView(sortExpression, DESCENDING);
        }
        else
        {
            GridViewSortDirection = SortDirection.Ascending;
            SortGridView(sortExpression, ASCENDING);
        }


    }

Use the following method for Sorting:
private void SortGridView(string sortExpression, string direction)
    {
        //  You can cache the DataTable for improving performance
        LoadGrid();
        DataTable dt = grdCause.DataSource as DataTable;
        DataView dv = new DataView(dt);
        dv.Sort = sortExpression + direction;

        grdCause.DataSource = dv;
        grdCause.DataBind();

    }
    private const string ASCENDING = " ASC";
    private const string DESCENDING = " DESC";

    public SortDirection GridViewSortDirection
    {
        get
        {
            if (ViewState["sortDirection"] == null)
                ViewState["sortDirection"] = SortDirection.Ascending;

            return (SortDirection)ViewState["sortDirection"];
        }
        set { ViewState["sortDirection"] = value;
 }
    }
 
Share this answer
 
Comments
Sahil sharma 29-Oct-12 3:25am    
I Want Sorting Implemented in window application not on web application
hi
try out this

using System;
using System.ComponentModel;
using System.Windows.Forms;

class Form1 : Form
{
    private Button sortButton = new Button();
    private DataGridView dataGridView1 = new DataGridView();

    // Initializes the form. 
    // You can replace this code with designer-generated code. 
    public Form1()
    {
        dataGridView1.Dock = DockStyle.Fill;
        dataGridView1.AllowUserToAddRows = false;
        dataGridView1.SelectionMode =
            DataGridViewSelectionMode.ColumnHeaderSelect;
        dataGridView1.MultiSelect = false;

        sortButton.Dock = DockStyle.Bottom;
        sortButton.Text = "Sort";

        Controls.Add(dataGridView1);
        Controls.Add(sortButton);
        Text = "DataGridView programmatic sort demo";
    }

    // Establishes the main entry point for the application.
    [STAThreadAttribute()]
    static void Main()
    {
        Application.EnableVisualStyles();
        Application.Run(new Form1());
    }

    // Populates the DataGridView. 
    // Replace this with your own code to populate the DataGridView. 
    public void PopulateDataGridView()
    {
        // Add columns to the DataGridView.
        dataGridView1.ColumnCount = 2;
        dataGridView1.Columns[0].HeaderText = "Last Name";
        dataGridView1.Columns[1].HeaderText = "City";
        // Put the new columns into programmatic sort mode
        dataGridView1.Columns[0].SortMode = 
            DataGridViewColumnSortMode.Programmatic;
        dataGridView1.Columns[1].SortMode =
            DataGridViewColumnSortMode.Programmatic;

        // Populate the DataGridView.
        dataGridView1.Rows.Add(new string[] { "Parker", "Seattle" });
        dataGridView1.Rows.Add(new string[] { "Watson", "Seattle" });
        dataGridView1.Rows.Add(new string[] { "Osborn", "New York" });
        dataGridView1.Rows.Add(new string[] { "Jameson", "New York" });
        dataGridView1.Rows.Add(new string[] { "Brock", "New Jersey" });
    }

    protected override void OnLoad(EventArgs e)
    {
        sortButton.Click += new EventHandler(sortButton_Click);

        PopulateDataGridView();
        base.OnLoad(e);
    }

    private void sortButton_Click(object sender, System.EventArgs e)
    {
        // Check which column is selected, otherwise set NewColumn to null.
        DataGridViewColumn newColumn =
            dataGridView1.Columns.GetColumnCount(
            DataGridViewElementStates.Selected) == 1 ?
            dataGridView1.SelectedColumns[0] : null;

        DataGridViewColumn oldColumn = dataGridView1.SortedColumn;
        ListSortDirection direction;

        // If oldColumn is null, then the DataGridView is not currently sorted. 
        if (oldColumn != null)
        {
            // Sort the same column again, reversing the SortOrder. 
            if (oldColumn == newColumn &&
                dataGridView1.SortOrder == SortOrder.Ascending)
            {
                direction = ListSortDirection.Descending;
            }
            else
            {
                // Sort a new column and remove the old SortGlyph.
                direction = ListSortDirection.Ascending;
                oldColumn.HeaderCell.SortGlyphDirection = SortOrder.None;
            }
        }
        else
        {
            direction = ListSortDirection.Ascending;
        }

        // If no column has been selected, display an error dialog  box. 
        if (newColumn == null)
        {
            MessageBox.Show("Select a single column and try again.",
                "Error: Invalid Selection", MessageBoxButtons.OK,
                MessageBoxIcon.Error);
        }
        else
        {
            dataGridView1.Sort(newColumn, direction);
            newColumn.HeaderCell.SortGlyphDirection =
                direction == ListSortDirection.Ascending ?
                SortOrder.Ascending : SortOrder.Descending;
        }
    }
}
 
Share this answer
 
Comments
Sahil sharma 29-Oct-12 6:04am    
Hi ,
I am using dataDashBoardGridView_ColumnHeaderMouseClick event and dataDashBoardGridView.Columns.GetColumnCount(DataGridViewElementStates.Selected) line give me always 0 value.

Thanks
Try something Like this,
There's a method on the DataGridView called "Sort":

C#
this.dataGridView1.Sort(this.dataGridView1.Columns["Name"],ListSortDirection.Ascending);


This will programmatically sort your datagridview.

regards and thanks
sarva
 
Share this answer
 
Comments
Sahil sharma 29-Oct-12 5:28am    
Hi this.dataGridView1.Sort(this.dataGridView1.Columns["Name"],ListSortDirection.Ascending); i Used this method but there is problem in How can I get Sort Expression from DataTable Exmple Like
DataTable data = objAllDetail.Search();
How can I get Sort Expression of Datatable which I Declare upper
Thanks

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900