sort Gridview doesn't work

混江龙づ霸主 提交于 2019-12-24 02:44:31

问题


I have asp.net page contain gridview as following

<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>

I fill and sort it using the following code

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


    }

the problem when click on any header for sorting raise error System.IndexOutOfRangeException: Cannot find column name .. , any idea to solve that , I am sure from the columns name in database ,


回答1:


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

try this code..




回答2:


You need to bind your grid to the sorted view (and not the original table) for sorting to work.

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

I am not sure if you need GetSortDirection method.

Also note that SortExpression property consists of sort direction (e.g. "UID DESC") so base your logic on that. Your code could have set sort expression such as "UID DESC ASC" which is obviously a wrong expression.




回答3:


In order to have the code work in asp.net or a web environment, you need to put your gridview in Session a session object, and your sorting in a view state. In order to get the sorting to work with paging, do the following.

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;

}


来源:https://stackoverflow.com/questions/7594375/sort-gridview-doesnt-work

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