简体   繁体   English

使用DataTable作为数据源的GridView排序事件处理

[英]GridView Sorting Event Handling using a DataTable as DataSource

I have a GridView which Id is GridView1 inside a updatePanel, I have defined programatically most of the events, but I havent issues while creating the event handler for sorting, can you kindly look my code and suggest the way to implement the sortings event using the datatable below? 我在updatePanel中有一个GridView,其ID为GridView1,我已通过编程方式定义了大多数事件,但是在创建用于排序的事件处理程序时我没有遇到任何问题,您能否看一下我的代码并提出使用以下方法实现排序事件的方法的建议下面的数据表?

// Method to BinData to GridView1

private void BindData()
     {
         string strQuery = "SELECT * FROM [tbl_SignIns] ";
         SqlCommand cmd = new SqlCommand(strQuery);
         GridView1.DataSource = GetData(cmd);
         GridView1.DataBind();
     }

     private DataTable GetData(SqlCommand cmd)
     {
         DataTable dt = new DataTable();
         SqlConnection con = new SqlConnection(strConnString);
         SqlDataAdapter sda = new SqlDataAdapter();
         cmd.CommandType = CommandType.Text;
         cmd.Connection = con;
         con.Open();
         sda.SelectCommand = cmd;
         sda.Fill(dt);
         return dt;
     }


 protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
     {

?????????????????????????????????

     }

I had a same problem and i solve like this. 我有一个同样的问题,我这样解决。 First I added up and down arrow on gridview header. 首先,我在gridview标头上添加了向上和向下箭头。

     <asp:TemplateField FooterText="Toplam" HeaderText="---">
 <HeaderTemplate>
 <asp:Label ID="Label4" runat="server" Text="---"></asp:Label><br />
 <br />
 <div id="myelement">
 <asp:ImageButton ID="btnDateUp" runat="server" ImageUrl="~/Admin/skins/Skin_1/images/grid_uparrow.png"
 OnClick="btnDateUp_Click" />
 <asp:ImageButton ID="btnDateDown" runat="server" ImageUrl="~/Admin/skins/Skin_1/images/grid_downarrow.png"
 OnClick="btnDateDown_Click" Style="width: 16px" />
 </div>
 </HeaderTemplate>
 <ItemTemplate>
 <asp:Label ID="Label3" runat="server" Text='<%# Bind("OrderDate", "{0:D}") %>'></asp:Label>
 </ItemTemplate>
 <ItemStyle HorizontalAlign="Left" Width="210px" />
 </asp:TemplateField>

After, I prepared my sql query like this ; 之后,我准备了这样的sql查询;

protected void btnDateUp_Click(object sender, ImageClickEventArgs e)
    {
        sortingQuery = " ORDER BY OrderDate DESC ";
        if (radioListReport.SelectedValue == "1")
            SortGrid();
        else
            SortQuarterGrid();

        updatePanelGrid.Update();
    }

protected void btnDateDown_Click(object sender, ImageClickEventArgs e)
    {
        sortingQuery = " ORDER BY OrderDate ASC ";
        if (radioListReport.SelectedValue == "1")
            SortGrid();
        else
            SortQuarterGrid();

        updatePanelGrid.Update();
    }

I hope it ll help you. 希望对您有帮助。

You will have to create tow viewstates one for the sort direction and the other for sort expression for checking while sorting. 您将必须创建两个视图状态,一个用于排序方向,另一个用于排序表达式,以便在排序时进行检查。

First, Sort Direction is retrieved from gridview as "Ascending" and "Descending" and when you want to filer data in the datatable you have to use "ASC" and "DESC" that passes the gridview sort direction and then retirevs it's according value when sorting the datable. 首先,将排序方向从“网格视图”中检索为“升序”和“降序”,并且当您要在数据表中归档数据时,必须使用“ ASC”和“ DESC”,它们通过了网格视图的排序方向,然后在达到该值时退回排序数据。

Second, A flip function that will passes a the sort direction and will flip it, and it's used when you click the first time on the columon it will sort "ASC" for example then the second time you click on it, it have to be "DESC" thats why i flip it. 其次,翻转函数将传递排序方向并将其翻转,并且在您第一次单击列时会使用它,例如,它将对“ ASC”进行排序,然后在您第二次单击时进行排序“ DESC”这就是我翻转它的原因。

Third, Viewstates are used to withhold the values of the previous sort. 第三,Viewstate用于保留上一类的值。

Fourth, Create a viewstate to hold the sort datatable for PageIndexChanging event, ofcourse you will have to check if the viewstate is null then you will have to fetch data and bind it, else you will have to bind the gridview with sorted datatable. 第四,创建一个viewstate来保存PageIndexChanging事件的排序数据表,当然,您必须检查viewstate是否为null,然后必须获取数据并将其绑定,否则必须将gridview与已排序的数据表绑定。

protected void GridView_Users_Sorting(object sender, GridViewSortEventArgs e)
{
    if (String.IsNullOrEmpty(ViewState["sortExpression"].ToString()) && String.IsNullOrEmpty(ViewState["sortDirection"].ToString()))
    {
      //Sort and bind data as ASCENDING for the first time
      DefaultSortBind(e);
    }
    else
    {
        if (ViewState["sortExpression"].ToString() == e.SortExpression.ToString())
        {
            string sortDirection = string.Empty;
            if (ViewState["sortDirection"].ToString() == e.SortDirection.ToString())
            {
                sortDirection = flipSortDirection(GetSortDirection(e.SortDirection.ToString()));
            }
            else
            {
                sortDirection = GetSortDirection(e.SortDirection.ToString());
            }

            DataTable dt = new UserInfoTableTableAdapter().GetData();
            dt.DefaultView.Sort = e.SortExpression + " " + sortDirection;
            GridView_Users.DataSource = dt.DefaultView;
            GridView_Users.DataBind();
            ViewState["sortedDt"] = dt.DefaultView.ToTable();
            ViewState["sortDirection"] = sortDirection;
        }
        else
        {
            //Sort and bind data as ASCENDING
            DefaultSortBind(e);
        }
    }
}

    private void DefaultSortBind(GridViewSortEventArgs e)
{
    ViewState["sortExpression"] = e.SortExpression;
    ViewState["sortDirection"] = e.SortDirection;
    //Fetch data again, because if we try to get data from gridview it will give null
    DataTable dt = new UserInfoTableTableAdapter().GetData();
    dt.DefaultView.Sort = e.SortExpression + " " + GetSortDirection(e.SortDirection.ToString());
    GridView_Users.DataSource = dt.DefaultView;
    GridView_Users.DataBind();
    ViewState["sortedDt"] = dt.DefaultView.ToTable();
}

    //Get sort direction
private string GetSortDirection(string sortDirection)
{
    if (sortDirection == "Ascending")
    {
        return "ASC";
    }
    else
    {
        return "DESC";
    }
}

//Flip sort direction
private string flipSortDirection(string sortDirection)
{
    if (sortDirection == "ASC")
    {
        return "DESC";
    }
    else
    {
        return "ASC";
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM