GridView with Paging and Sorting

Filed Under (ASP.NET, C#) by admin on 15-12-2008

ASPX page

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" AllowPaging="True"
        OnSelectedIndexChanged="GridView1_SelectedIndexChanged" OnPageIndexChanging="GridView1_PageIndexChanging"
        AllowSorting="True" OnSorting="GridView1_Sorting" EmptyDataText="No records found" PageSize="10"
        PagerSettings-Mode="NumericFirstLast">
        <Columns>
            <asp:BoundField DataField="clnID" HeaderText="ID" ItemStyle-CssClass="generic_gridview_hidecolumn"
                HeaderStyle-CssClass="generic_gridview_hidecolumn" >
<HeaderStyle CssClass="generic_gridview_hidecolumn"></HeaderStyle>

<ItemStyle CssClass="generic_gridview_hidecolumn"></ItemStyle>
            </asp:BoundField>
            <asp:HyperLinkField DataNavigateUrlFields="clnID" DataNavigateUrlFormatString="customer-details.aspx?ID={0}"
                DataTextField="clnLastName" Text="&nbsp;Name" HeaderText="&nbsp;Name" SortExpression="clnLastName"/>
            <asp:BoundField DataField="clnAddress1" HeaderText="Address" SortExpression="clnAddress1" />
            <asp:BoundField DataField="clnCity" HeaderText="City" SortExpression="clnCity" />
            <asp:BoundField DataField="clnPhone" HeaderText="Phone" SortExpression="clnPhone"/>
        </Columns>
    </asp:GridView>

CODE BEHIND page

 

public partial class application_customers_customer_list : System.Web.UI.Page
{
    //read the connection string from web.config
    public static string connectionString = ConfigurationManager.ConnectionStrings[
        "CartConnectionString"].ConnectionString;

    public SortDirection SortDir
    {
        get
        {
            if (ViewState["sortDirection"] == null)
            {
                ViewState["sortDirection"] = SortDirection.Ascending;
            } return (SortDirection)ViewState["sortDirection"];
        }
        set
        {
            ViewState["sortDirection"] = value;
        }
    }

    DataSet ds = new DataSet();
    DataView dv = new DataView();
    SqlConnection conn = new SqlConnection();
    SqlDataAdapter da = new SqlDataAdapter();

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            BindGrid();
            GridView1.DataSource = dv;
            GridView1.DataBind();
        }
    }

    private DataView BindGrid()
    {
        //Generate the SQL
        StringBuilder SQL = new StringBuilder();
        SQL.Append(" SELECT *");
        SQL.Append(" FROM client");

        string searchTxt = txtSearch.Text;

        // Has the user searched for anything?
        if (searchTxt.Length > 0)
        {
            SQL.Append(" WHERE clnLastName LIKE '%" + searchTxt + "%' ");
            SQL.Append(" OR clnAddress1 LIKE '%" + searchTxt + "%' ");
            SQL.Append(" OR clnCity LIKE '%" + searchTxt + "%' ");
            SQL.Append(" OR clnPhone LIKE '%" + searchTxt + "%' ");
        }

        //Initialize connection
        conn = new SqlConnection(connectionString);

        da = new SqlDataAdapter(SQL.ToString(), conn);
        da.Fill(ds);

        if (ViewState["sortExpr"] != null)
        {
            dv = new DataView(ds.Tables[0]);
            dv.Sort = (string)ViewState["sortExpr"];
        }
        else
        {
            dv = ds.Tables[0].DefaultView;
        }

        return dv;
    }

    protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        GridView1.PageIndex = e.NewPageIndex;
        GridView1.DataSource = BindGrid();
        GridView1.DataBind();
    }

    protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
    {
        string stExp = e.SortExpression;
        string stDir = string.Empty;
        if (SortDir == SortDirection.Ascending)
        {
            SortDir = SortDirection.Descending;
            stDir = "DESC";
        }
        else
        {
            SortDir = SortDirection.Ascending;
            stDir = "ASC";
        }

        ViewState["sortExpr"] = e.SortExpression + " " + stDir;
        GridView1.DataSource = BindGrid();
        GridView1.DataBind();
    }

    protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
    {
        int selectedRowIndex;
        selectedRowIndex = GridView1.SelectedIndex;
        GridViewRow row = GridView1.Rows[selectedRowIndex];
        string ID = row.Cells[0].Text;

        Response.Redirect("customer-details.aspx?ID=" + ID, false);
    }

    protected void btnSearch_Click(object sender, EventArgs e)
    {
        BindGrid();
    }

}

Leave a Reply