0

I want to sort the columns of the grid view. Can anyone explain me the process. What methods I need and how to do it. I looked on the internet found some but they seem not to work. I finally went with http://msdn.microsoft.com/en-us/librar/system.web.ui.webcontrols.gridview.sortexpression%28v=vs.110%29.aspx and when I click on the arrow it doesn't do anything. When I click on the column name I get: System.Web.HttpException: The GridView 'GridView1' fired event Sorting which wasn't handled.

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

Also, how can I add the image to all columns?

    protected void GridView1_RowCreated(Object sender, GridViewRowEventArgs e)
    {

        // Use the RowType property to determine whether the 
        // row being created is the header row. 
        if (e.Row.RowType == DataControlRowType.Header)
        {
            // Call the GetSortColumnIndex helper method to determine
            // the index of the column being sorted.
            int sortColumnIndex = GetSortColumnIndex();

            if (sortColumnIndex != -1)
            {
                // Call the AddSortImage helper method to add
                // a sort direction image to the appropriate
                // column header. 
                AddSortImage(sortColumnIndex, e.Row);
            }
        }
    }

   private int GetSortColumnIndex(int p)
   {
       throw new NotImplementedException();
   }

    // This is a helper method used to determine the index of the
    // column being sorted. If no column is being sorted, -1 is returned.
   protected int GetSortColumnIndex()
    {

        // Iterate through the Columns collection to determine the index
        // of the column being sorted.
        foreach (DataControlField field in GridView1.Columns)
        {
            if (field.SortExpression == GridView1.SortExpression)
            {
                return GridView1.Columns.IndexOf(field);
            }
        }

        return -1;
    }


    // This is a helper method used to add a sort direction
    // image to the header of the column being sorted.
  protected  void AddSortImage(int columnIndex, GridViewRow headerRow)
    {

        // Create the sorting image based on the sort direction.
        Image sortImage = new Image();
        if (GridView1.SortDirection == SortDirection.Ascending)
        {
            sortImage.ImageUrl = "~/images/arrowasc.png";
            sortImage.AlternateText = "Ascending Order";
        }
        else
        {
            sortImage.ImageUrl = "~/images/arrowdesc.png";
            sortImage.AlternateText = "Descending Order";
        }

        // Add the image to the appropriate header cell.
        headerRow.Cells[2].Controls.Add(sortImage);
    }

1 Answer 1

0

Here is a quick guide to have a grid view with sorting function:

your .aspx page (a GridView with two columns):

<asp:GridView ID="gridExistingQuestions" runat="server"
              AutoGenerateColumns="False" GridLines="Vertical" 
              EmptyDataText="No Question Found." AllowSorting="True"
              OnSorting="gridExistingInterviewQuestions_Sorting" >
    <Columns>
       <asp:TemplateField HeaderText="Question Title" SortExpression="Title">
          <ItemTemplate>
             <asp:Label ID="lblQuestionTitle" runat="server" 
                        Text='dynamic title here'></asp:Label>
          </ItemTemplate>
       </asp:TemplateField>
       <asp:TemplateField HeaderText="Question Desc" SortExpression="Desc">  
          <ItemTemplate>
             <asp:Label ID="lblQuestionDesc" runat="server" 
                        Text='dynamic Desc here'></asp:Label>
          </ItemTemplate>
      </asp:TemplateField>
    </Columns>
</asp:GridView>

your aspx.cs page

 DataTable questionTable;
 DataView questionView;

 this.SetQuestionData();
    //on page gridview sorting
    protected void gridExistingQuestions_Sorting(object sender, GridViewSortEventArgs e)
    {
        try
        {
            CurrentView = e.SortExpression + " " + this.ConvertSortDirectionToSql(e, "question");
            if (questionView != null)
            {
                questionView.Sort = CurrentView;

                // bind your grid view here ...
            }
            else
                this.SetQuestionData();
        }
        catch { // display error }
    }

    private string CurrentView
    {
        get { return (string)(ViewState["vsCurrentView"] ?? (object)null); }
        set { ViewState["vsCurrentView"] = value; }
    }

    //handling sorting function
    private string ConvertSortDirectionToSql(GridViewSortEventArgs e, string key)
    {
        ViewState[key + e.SortExpression] = ViewState[key + e.SortExpression] ?? "ASC";
        ViewState[key + e.SortExpression] = (ViewState[key + e.SortExpression].ToString() == "ASC") ? "DESC" : "ASC";
        return ViewState[key + e.SortExpression].ToString();
    }

    private bool SetQuestionData()
    {
        questionTable = //get your data from db

        if (questionTable != null)
        {
            questionView = new DataView(questionTable);

            if (!string.IsNullOrEmpty(CurrentView))
                QuestionView.Sort = CurrentView;

            // bind your grid view here
            return true;
        }
        return false;
    }

and you can use ConvertSortDirectionToSql() method for all other grid views on your page as well.

hope it gives you a clue and REMEMBER you need to bind your data at the commented spots

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.