排序Gridview不起作用

时间:2011-09-29 08:19:29

标签: c# asp.net gridview c#-3.0

我的asp.net页面包含gridview,如下所示

<asp:GridView ID="GridView1" runat="server" AllowPaging="True" 
                    OnPageIndexChanging="gridView_PageIndexChanging" 
                    OnSorting="TaskGridView_Sorting"
                    AllowSorting="True"  AutoGenerateColumns="False" 
                    onselectedindexchanged="GridView1_SelectedIndexChanged" 
                    BackColor="#DEBA84" BorderColor="#DEBA84" BorderStyle="None" BorderWidth="1px" 
                    CellPadding="3" CellSpacing="2">
                    <RowStyle BackColor="#FFF7E7" ForeColor="#8C4510" />
                    <Columns>
                      <asp:boundfield datafield="name_english" convertemptystringtonull="true" headertext="Name"/>
                        <asp:BoundField DataField="Inc_ID" convertemptystringtonull="true" HeaderText="Inc_ID" SortExpression="Inc_ID"/>
                        <asp:BoundField DataField="UID" HeaderText="Study_UID" SortExpression= "UID"/>
                    </Columns>
                    <FooterStyle BackColor="#F7DFB5" ForeColor="#8C4510" />
                    <PagerStyle ForeColor="#8C4510" HorizontalAlign="Center" />
                    <SelectedRowStyle BackColor="#738A9C" Font-Bold="True" ForeColor="White" />
                    <HeaderStyle BackColor="#A55129" Font-Bold="True" ForeColor="White" />
                </asp:GridView>

我使用以下代码填写并对其进行排序

        protected void Button1_Click(object sender, EventArgs e)
        {
            //connection to database 
            string connection = System.Configuration.ConfigurationManager.ConnectionStrings["NorthindConnectionString"].ConnectionString;
            SqlConnection myConn = new SqlConnection(connection);
            myConn.Open();
            SqlCommand cmd = new SqlCommand(" WorkList", myConn);
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.Add(new SqlParameter("@Name", TextBox1.Text));
            cmd.Parameters.Add(new SqlParameter("@ID", TextBox2.Text)); 
            cmd.Parameters.Add(new SqlParameter("@AccNo", TextBox4.Text)); 


            SqlDataAdapter da = new SqlDataAdapter(cmd);
            DataSet ds = new DataSet();
            da.Fill(ds);
            GridView1.DataSource = ds;
            GridView1.DataBind();

            Session["TaskTable"] = ds.Tables[0]; 

            ds.Dispose();
            da.Dispose();
            GridView1.Visible = true;

            myConn.Close();


        }
 protected void TaskGridView_Sorting(object sender, GridViewSortEventArgs e)
        {

            //Retrieve the table from the session object.
            DataTable dt = Session["TaskTable"] as DataTable;

            if (dt != null)
            {

                //Sort the data.
                dt.DefaultView.Sort = e.SortExpression + " " + GetSortDirection(e.SortExpression);
                GridView1.DataSource = Session["TaskTable"];
                GridView1.DataBind();
            }

        }



        private string GetSortDirection(string column)
        {

            // By default, set the sort direction to ascending.
            string sortDirection = "ASC";

            // Retrieve the last column that was sorted.
            string sortExpression = ViewState["SortExpression"] as string;

            if (sortExpression != null)
            {
                // Check if the same column is being sorted.
                // Otherwise, the default value can be returned.
                if (sortExpression == column)
                {
                    string lastDirection = ViewState["SortDirection"] as string;
                    if ((lastDirection != null) && (lastDirection == "ASC"))
                    {
                        sortDirection = "DESC";
                    }
                }
            }

            // Save new values in ViewState.
            ViewState["SortDirection"] = sortDirection;
            ViewState["SortExpression"] = column;

            return sortDirection;
        }


    }

单击任何标题进行排序时出现问题引发错误System.IndexOutOfRangeException:找不到列名..,任何想法解决这个问题,我肯定从数据库中的列名,

3 个答案:

答案 0 :(得分:4)

private string ConvertSortDirectionToSql(SortDirection sortDirection)
    {
        string newSortDirection = String.Empty;

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

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

        return newSortDirection;
    }


    protected void gridView_Sorting(object sender, GridViewSortEventArgs e)
    {
        DataTable dataTable = gridView.DataSource as DataTable;

        if (dataTable != null)
        {
            DataView dataView = new DataView(dataTable);
            dataView.Sort = e.SortExpression + " " + ConvertSortDirectionToSql(e.SortDirection);

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

试试这段代码..

答案 1 :(得分:2)

您需要将网格绑定到已排序的视图(而不是原始表),以便进行排序。

protected void TaskGridView_Sorting(object sender, GridViewSortEventArgs e)
{
    //Retrieve the table from the session object.
    DataTable dt = Session["TaskTable"] as DataTable;

    if (dt != null)
    {

        //Sort the data.
        dt.DefaultView.Sort = e.SortExpression;
        GridView1.DataSource = dt.DefaultView;
        GridView1.DataBind();
    }
}

我不确定您是否需要GetSortDirection方法。

另请注意,SortExpression属性包含排序方向(例如“UID DESC”),因此将逻辑基于此。您的代码可以设置排序表达式,例如“UID DESC ASC”,这显然是一个错误的表达。

答案 2 :(得分:1)

为了使代码在asp.net或Web环境中工作,您需要将您的gridview在Session中放入会话对象,并将您的排序放在视图状态中。为了使分页与分页一起使用,请执行以下操作。

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    { 
      Session["SearchTable"] = gv_GridView.DataSource;
      LoadSearchGrid("Select * from WF_Search);
}
private void LoadSearchGrid(string query)
{
    DataTable dsp = new DataTable();
    conn = new SqlConnection(ConnectionString);
    SqlDataAdapter sda = new SqlDataAdapter(query, conn);
    conn.Open();
    sda.Fill(dsp);
    Session["SearchTable"] = dsp;
    gv_GridView.DataSource = Session["SearchTable"];
    gv_GridView.DataBind();
    conn.Close();
    sda.Dispose();
}
protected void gv_GridView_Sorting(object sender, GridViewSortEventArgs e)
{
    ViewState["SortDirection"] = e.SortDirection;
    DataTable dtr = Session["SearchTable"] as DataTable;
    if (dtr != null)
    {
        dtr.DefaultView.Sort = e.SortExpression + " " + getSortDirection(e.SortExpression);
        gv_GridView.DataSource = Session["SearchTable"];
        gv_GridView.DataBind();
        Session["SearchTable"] = gv_GridView.DataSource;
    }
}
private string getSortDirection(string column)
{
    string sortDirection = "ASC";
    string sortExpression = ViewState["SortDirection"] as string;
    if (sortExpression != null)
    {
        if (sortExpression == column)
        {
            string lastDirection = ViewState["SortDirection"] as string;
            if (lastDirection != null && lastDirection == "ASC")
            {
                sortDirection = "DESC";
            }
        }
    }
    ViewState["SortDirection"] = sortDirection;
    ViewState["SortExpression"] = column;

    return sortDirection;
}
protected void gv_GridView_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
    gv_GridView.DataSource = Session["SearchTable"];
    gv_GridView.DataBind();
    gv_GridView.PageIndex = e.NewPageIndex;

}