如何对页面加载进行排序,并在GridView中显示基于排序的图像

时间:2014-08-06 03:37:06

标签: c# asp.net sorting gridview

我有以下代码(asp.net和代码隐藏)来实现排序:

protected void Page_Load(object sender, EventArgs e)
{

    if (!Page.IsPostBack)
    {
        PullData("", "");
        ViewState["sortOrder"] = "";
    }
}
public void PullData(string sortExp, string sortDir)
{
    DataTable taskData = new DataTable();
    string connString = @"user id = dsfsdfds;" + "password= sadasdada; server=  mg; database= ob;" /*+ "Trusted_Connection=yes;"*/  + "connection timeout=30";
    string query = @"SELECT  'http://mg/appnet/workview/objectPop.aspx?objectid=' + CAST(CT.OBJECTID AS VARCHAR) + '&classid=1224' 'Task Detail'
            ,UG.USERGROUPNAME 'Services'
            ,CT.ATTR2812 'Status'
            ,CT.ATTR2752 'Due Date'
            ,CT.ATTR2739 'Task Name'

        FROM dbo.RMOBJECTINSTANCE1224 CT
        WHERE CT.ACTIVESTATUS = 0";

    using (SqlConnection conn = new SqlConnection(connString))
    {
        try
        {
            SqlCommand cmd = new SqlCommand(query, conn);

            // create data adapter
            SqlDataAdapter da = new SqlDataAdapter(query, conn);
            // this will query your database and return the result to your datatable

            DataSet myDataSet = new DataSet();
            da.Fill(myDataSet);

            DataView myDataView = new DataView();
            myDataView = myDataSet.Tables[0].DefaultView;

            if (sortExp != string.Empty)
            {
                myDataView.Sort = string.Format("{0} {1}", sortExp, sortDir);
            }

            yourTasksGV.DataSource = myDataView;
            yourTasksGV.DataBind();

            conn.Close();
        }
        catch (Exception ex)
        {
            string error = ex.Message;
        }
    }
}

protected void yourTasksGV_Sorting(object server, GridViewSortEventArgs e)
{
    PullData(e.SortExpression, sortOrder);
}
public string sortOrder
{
    get
    {
        if (ViewState["sortOrder"].ToString() == "Desc")
        {
            ViewState["sortOrder"] = "Asc";
        }
        else
        {
            ViewState["sortOrder"] = "Desc";
        }

        return ViewState["sortOrder"].ToString();
    }
    set
    {
        ViewState["sortOrder"] = value;
    }
}

我的GridView

<asp:GridView AlternatingRowStyle-BackColor="#E2E2E2" AutoGenerateColumns="false" OnSorting="yourTasksGV_Sorting" AllowSorting="true" ID="yourTasksGV" runat="server" ClientIDMode="Static" EmptyDataText="There is no data to display" OnRowDataBound="yourTasksGV_RowDataBound" OnRowCreated="yourTasksGV_RowCreated">
    <Columns>
        <asp:HyperLinkField Target="_blank" DataNavigateUrlFields="Task Detail" DataTextField="Task Name" DataNavigateUrlFormatString="" HeaderText="Task Details" SortExpression="Task Detail" ItemStyle-Width="35%" ItemStyle-CssClass="taskTableColumn" />
        <asp:BoundField DataField="Services" HeaderText="Services" SortExpression="Services" ItemStyle-Width="25%" ItemStyle-CssClass="taskTableColumn" />
        <asp:BoundField DataField="Status" HeaderText="Status" SortExpression="Status" ItemStyle-Width="15%" ItemStyle-CssClass="taskTableColumn" />
        <asp:BoundField DataField="Due Date" HeaderText="Due Date" SortExpression="Due Date" ItemStyle-Width="15%" ItemStyle-CssClass="taskTableColumn" />
    </Columns>
</asp:GridView>

对于第一列,我正在使用Task Name并显示SQL查询中Task Detail列中链接的显示文本(DataTextField是任务名称而不是任务详细信息)。

如何修改代码以执行以下操作:

  1. 当我点击Task Details标签时,它应按Task Name排序,该Task Detail显示为GridView的链接显示?
  2. 在我正在对表格进行排序的标题文本旁边显示图像? (up.png and down.png)?
  3. 在页面加载时,按#1 ASC排序并分别显示图像?
  4. 向用户显示我的href(请注意Task Name内的第一列链接使用情况以及显示文字是{{1}}):

    enter image description here

1 个答案:

答案 0 :(得分:1)

这里有一个有用的解决方案:

http://blogs.msdn.com/b/scothu/archive/2010/08/28/gridview-with-sort-arrows-and-showing-header-when-empty.aspx

你可以这样做 显示图像使用此代码:

protected void gv_RowCreated(object sender, GridViewRowEventArgs e)
{
    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);
        }
    }
}

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

    return -1;
}

    void AddSortImage(GridViewRow headerRow) 
{ 
     int iCol = GetSortColumnIndex();
     if (-1 == iCol) 
           return; 

     // Create the sorting image based on the sort direction.

     Image sortImage = new Image();
     if (SortDirection.Ascending == this.GridView1.SortDirection) 

{             sortImage.ImageUrl = @"~\Images\BlackDownArrow.gif"; 
               sortImage.AlternateText = "Ascending Order"; 
}     else  
{
             sortImage.ImageUrl = @"~\Images\BlackUpArrow.gif";
             sortImage.AlternateText = "Descending Order";
}
      // Add the image to the appropriate header cell. 
        headerRow.Cells[iCol].Controls.Add(new LiteralControl("&nbsp;"));
        headerRow.Cells[iCol].Controls.Add(sortImage); 
} 

并进行排序,启用gridview&#34;允许属性&#34;并添加`Sort Expression&#34;到列属性。