GridView Sorting Tutorial

穿精又带淫゛_ 提交于 2019-12-13 04:59:30

问题


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:


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



来源:https://stackoverflow.com/questions/23748174/gridview-sorting-tutorial

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!