Click here to Skip to main content
15,894,285 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
hi,
i have grid view and i have child controls like add edit update and delete
i want to sort the records when i click on any column name
please help me

my code is
C#
private string ConvertSortDirectionToSql1(SortDirection sortDirection)
{
    string newSortDirection = String.Empty;

    switch (sortDirection)
    {
        case SortDirection.Ascending:
            newSortDirection = "ASC";
            break;

        case SortDirection.Descending:
            newSortDirection = "DESC";
            break;
    }

    return newSortDirection;
}


protected void gvbgLabel_Sorting(object sender, GridViewSortEventArgs e)
{
    try
    {
        //Response.Write(gvallRecord.DataSource.GetType()); //Add this line
        DataTable dataTable = ((DataSet)Session["dtClass"]).Tables[0];

        if (gvbgLabel.Rows.Count >= 0)
        {
            DataView dataView = new DataView(dataTable);
            dataView.Sort = e.SortExpression + " " + ConvertSortDirectionToSql1(e.SortDirection);

            gvbgLabel.DataSource = dataView;
            gvbgLabel.DataBind();
        }

    }
    catch (Exception ex)
    {

    }


}


[edit]Code block added - OriginalGriff[/edit]
Posted
Updated 9-Aug-11 1:18am
v2
Comments
Herman<T>.Instance 9-Aug-11 7:22am    
have you set the allowsorting property of the gridview to true?

good examples are found here: http://msdn.microsoft.com/en-us/library/aa479347.aspx[^]

I use in the aspx:
 <asp:GridView runat="server" ID="grdServiceMessage" AutoGenerateColumns="false" AllowSorting="true"
             PagerSettings-Mode="NumericFirstLast" PagerSettings-Visible="true" PagerSettings-Position="TopAndBottom"
             AllowPaging="true" PageSize="20"
             OnPageIndexChanging="grdServiceMessage_OPIC"
             OnSorting="grdServiceMessage_OS"
             Caption="Messages"
             EmptyDataText="No Valid information found in searching"
            >
......


In code behind:
C#
protected void grdServiceMessage_OS(Object sender, GridViewSortEventArgs e)
    {
        Session["Column"] = e.SortExpression;
        if (rblSortOrder.SelectedValue.StartsWith(" ASC"))
            e.SortDirection = SortDirection.Ascending;
        else
            e.SortDirection = SortDirection.Descending;
        FillGridView(Session["Column"].ToString(),txtFilter.Text, grdServiceMessage.PageIndex);
    }

the FillGridview method:
C#
private void FillGridView(String ColumnNameToSortOn, String Filter, Int32 PageNr)
    {
        List<sqlparameter> parms = new List<sqlparameter>();
        try
        {
            if (txtStartDate.Text.Trim().Equals(String.Empty))
                txtStartDate.Text = DateTime.Now.AddDays(-DateTime.Now.Day).ToShortDateString();
            if (txtEndDate.Text.Trim().Equals(String.Empty))
                txtEndDate.Text = DateTime.Now.ToShortDateString();
            parms.Add(new SqlParameter("@ServiceID", ddlService.SelectedValue));
            parms.Add(new SqlParameter("@StartDate", Convert.ToDateTime(txtStartDate.Text + " 0:00:00")));
            parms.Add(new SqlParameter("@EndDate", Convert.ToDateTime(txtEndDate.Text + " 23:59:59")));
            DataView view = new DataView();
            String ConCatFilter = String.Empty;
            if (!Filter.Equals(String.Empty))
            {
                if (!ColumnNameToSortOn.Equals("lastModified", StringComparison.OrdinalIgnoreCase))
                {
                    ConCatFilter = ColumnNameToSortOn + " Like '%" + Filter + "%'";
                    lblError.Text = String.Empty;
                }
                else
                    lblError.Text = "Filtering on field 'Occurred' is not possible";
            }
            
                
//loads the data from db into dataview component, is my own library
            SyConOSDBClass.WebControls.UpdateDataView(view, "SE_SelMessageData", parms, ColumnNameToSortOn + rblSortOrder.SelectedValue, ConCatFilter);
            if (view.Count.Equals(0)) // Nothing found!
                grdServiceMessage.EmptyDataText = "Search for column '" + ColumnNameToSortOn + "' with Filter '" + ConCatFilter + "' Lead to no results.";
            grdServiceMessage.DataSource = view;
            grdServiceMessage.PageIndex = PageNr;
            grdServiceMessage.DataBind();
            Sesame.StyleSortableGridView(grdServiceMessage);
            Session["Column"] = ColumnNameToSortOn;
            
        }
        catch (Exception err)
        {
            lblError.Text = err.Message;
            ...
        }
        finally
        {
            ....
        }
    }
</sqlparameter></sqlparameter>
 
Share this answer
 
v2
 
Share this answer
 
 
Share this answer
 
protected void grd_Sorting(object sender, GridViewSortEventArgs e)
        {
            String sortExpression = e.SortExpression;
            m_strSortExpLead = "abc";
            m_strSortExp = e.SortExpression;


            if (dvLeadData.Table.Rows.Count > 0)
            {
                
                DataView dv = GetData();
                if (GridViewSortDirection == SortDirection.Ascending)
                {

                    
                    ViewState["sortDirection"] = SortDirection.Descending;
                    dv.Sort = sortExpression + " DESC";
                    grd.DataSource = dv;
                    grd.DataBind();
                }
                else
                {
                   
                    ViewState["sortDirection"] = SortDirection.Ascending;
                    dv.Sort = sortExpression + " ASC";
                    grd.DataSource = dv;
                    grd.DataBind();
                }
            }

        }
public SortDirection GridViewSortDirection
        {
            get
            {
                if (ViewState["sortDirection"] == null || ((SortDirection)ViewState["sortDirection"]) == SortDirection.Descending)
                    ViewState["sortDirection"] = SortDirection.Descending;
                else
                    ViewState["sortDirection"] = SortDirection.Ascending;
             
                return (SortDirection)ViewState["sortDirection"];
            }
            set { ViewState["sortDirection"] = value; }
        }



Hope this will help you for sure..
 
Share this answer
 

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