GridView排序教程 [英] GridView Sorting Tutorial

查看:283
本文介绍了GridView排序教程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想对网格视图的列进行排序。任何人都可以解释我的过程。我需要什么方法以及如何去做。我在网上找了一些发现,但他们似乎没有工作。我终于与
http://msdn.microsoft.com/en-us/librar/system.web.ui.webcontrols.gridview.sortexpression%28v=vs.110%29.aspx 和何时我点击它没有做任何事情的箭头。当我点击列名时,我得到:System.Web.HttpException:GridView'GridView1'触发了未处理的事件Sorting。



产生未处理的异常在执行当前Web请求期间。有关异常来源和位置的信息可以使用下面的异常堆栈跟踪来标识。

另外,如何将图像添加到所有列?

  protected void GridView1_RowCreated(Object sender,GridViewRowEventArgs e)
{

//使用RowType属性确定创建的
//行是否为标题行。
if(e.RowType == DataControlRowType.Header)
{
//调用GetSortColumnIndex帮助器方法来确定
//被排序列的索引。
int sortColumnIndex = GetSortColumnIndex();

if(sortColumnIndex!= -1)
{
//调用AddSortImage帮助器方法将
//一个排序方向图像添加到适当的
//列标题。
AddSortImage(sortColumnIndex,e.Row);



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

//这是一个辅助方法,用于确定正在排序的
//列的索引。如果没有列正在排序,则返回-1。
protected int GetSortColumnIndex()
{

//遍历Columns集合以确定要排序的列的索引
//。
foreach(GridView1.Columns中的DataControlField字段)
{
if(field.SortExpression == GridView1.SortExpression)
{
return GridView1.Columns.IndexOf(field );
}
}

返回-1;
}


//这是一种辅助方法,用于将排序方向
//图像添加到被排序列的标题中。
protected void AddSortImage(int columnIndex,GridViewRow headerRow)
{

//根据排序方向创建排序图像。
Image sortImage = new Image();
if(GridView1.SortDirection == SortDirection.Ascending)
{
sortImage.ImageUrl =〜/ images / arrowasc.png;
sortImage.AlternateText =升序;
}
else
{
sortImage.ImageUrl =〜/ images / arrowdesc.png;
sortImage.AlternateText =降序;
}

//将图像添加到相应的标题单元格中。
headerRow.Cells [2] .Controls.Add(sortImage);


解决方案

有一个带有排序功能的网格视图:

您的.aspx页面(一个带有两列的GridView):


 < asp:GridView ID =gridExistingQuestionsrunat =server
AutoGenerateColumns =FalseGridLines =垂直
EmptyDataText =找不到问题。 AllowSorting =True
OnSorting =gridExistingInterviewQuestions_Sorting>
<列>
< asp:TemplateField HeaderText =问题标题SortExpression =标题>
< ItemTemplate>
< asp:Label ID =lblQuestionTitlerunat =server
Text ='动态标题在这里>< / asp:Label>
< / ItemTemplate>
< / asp:TemplateField>
< asp:TemplateField HeaderText =问题描述SortExpression =Desc>
< ItemTemplate>
< asp:Label ID =lblQuestionDescrunat =server
Text ='dynamic Desc here'>< / asp:Label>
< / ItemTemplate>
< / asp:TemplateField>
< /列>
< / asp:GridView>


您的aspx.cs页面


  DataTable questionTable; 
DataView questionView;

this.SetQuestionData();
//在页面gridview排序
保护无效gridExistingQuestions_Sorting(对象发件人,GridViewSortEventArgs e)
{
尝试
{
CurrentView = e.SortExpression + + this.ConvertSortDirectionToSql(e,question);
if(questionView!= null)
{
questionView.Sort = CurrentView;

//在这里绑定你的网格视图...
}
else
this.SetQuestionData();
}
catch {//显示错误}
}

私有字符串CurrentView
{
get {return(string)(ViewState [ vsCurrentView] ??(object)null); }
set {ViewState [vsCurrentView] = value; }
}

//处理排序函数
私有字符串ConvertSortDirectionToSql(GridViewSortEventArgs e,字符串键)
{
ViewState [key + e.SortExpression] = ViewState [key + e.SortExpression] ?? ASC;
ViewState [key + e.SortExpression] =(ViewState [key + e.SortExpression] .ToString()==ASC)? DESC:ASC;
返回ViewState [key + e.SortExpression] .ToString();
}

private bool SetQuestionData()
{
questionTable = //从db获取数据

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

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

//在这里绑定你的网格视图
return true;
}
返回false;
}


,您可以使用ConvertSortDirectionToSql()方法对于您网页上的所有其他网格视图也是如此。



希望它提供了线索,记住,您需要在注释中绑定数据点


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);
    }

解决方案

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

这篇关于GridView排序教程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆