asp.netsortinggridviewpaginationsqldatasource

GridView Paging and Sorting


I have a GridView webcontrol that has paging and sorting enabled. I've bound the datasource to an SqlDataSource. When I try to change the page index or sort, I get a "GridView fired event [Sorting/PageIndexChanging] which wasn't handled" error. Isn't the SqlDataSource already equipeed to handle these events?

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%@language = "C#" Debug="true" src="ServerCode/Default.cs" Inherits="Home.Default" %>
<html>
<head>
    <title>APTEIT Data Preview</title>
</head>
<body>
    <form id = "mainFrm" runat = "server">
        <div id = "headersDiv">
            <asp:Table id = "headerTbl" runat = "server">
            </asp:Table>
        </div>
        <div id = "dataDiv">
            <asp:GridView id = "dataTbl" runat = "server" 
                ShowHeader="false"
                AllowPaging="true"
                GridLines="None" 
                AlternatingRowStyle="altRow"
                PagerStyle="pager"
                PageSize="50"
                >
            </asp:GridView>
        </div>
    </form>
</body>
</html>

CodeBehind

SqlDataSource sqlData = new SqlDataSource("Hidden for security reasons");
Select(DataSourceSelectArguments.Empty);
dataTbl.DataSource = sqlData;
dataTbl.DataBind();
headerTbl.Rows.Add(new TableRow());

Solution

  • You have to rebind GridView:

    private void BindData()
    {
        SqlDataSource sqlData = new SqlDataSource("Hidden for security reasons");
        Select(DataSourceSelectArguments.Empty);
        dataTbl.DataSource = sqlData;
        dataTbl.DataBind();
        headerTbl.Rows.Add(new TableRow());
    }
    
    protected void dataTbl_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        dataTbl.PageIndex = e.NewPageIndex;
        BindData();
    }
    

    In markup add to GridView:

    OnPageIndexChanging="dataTbl_PageIndexChanging"
    

    It should work.