Monday, May 4, 2009

Alphabetical Paging in Gridview

using System.Data.SqlClient;

public partial class alpahbetical_paging : System.Web.UI.Page
{
    string query;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (IsPostBack == false)
        {
            query = "select * from customers";
            FillGrid(query);
        }
    }

    private void FillGrid(string s)
    {
        SqlConnection con = new SqlConnection("trusted_connection=yes;database=northwind;server=localhost");
        SqlDataAdapter da = new SqlDataAdapter(query, con);
        DataSet ds = new DataSet();
        da.Fill(ds, "Customers");
        GridView1.DataSource = ds.Tables["Customers"];
        GridView1.DataBind();
    }

//The RowCreated event is used to create the list.

// In the event first  check for the footer row.

// Once, the footer row is found  run a loop from 65 to 92 and convert each number into the character representation.

// The number 65 stands for “A”, 66 for “B” and so on till 92 for “Z”. Inside the loop  create a LinkButton and set the Text property to the alphabet. Finally, the control is added to the cell collection.

//Creating the Alphabetical List:

//The next task is to create an alphabetical list and display it in the GridView control.

//The best place to display the list is the GridView footer.



    protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.Footer)
        {
            TableCell cell = e.Row.Cells[0];
            cell.ColumnSpan = 5;
            for (int i = 65; i <= (65 + 25); i++)
            {
                LinkButton lb = new LinkButton();
                lb.Text = Char.ConvertFromUtf32(i) + "";
                lb.CommandArgument = Char.ConvertFromUtf32(i);
                lb.CommandName = "AlphaPaging";
                cell.Controls.Add(lb);
            }
        }
    }

//Fetching the Records Based on the Alphabet:

//In the last section we created the alphabets and displayed them in the footer of the GridView control.

//The next task is to capture the event generated by the alphabets when we click on them and fetch the results based on the alphabet. The RowCommand event is fired whenever you click on any alphabet.



    protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if(e.CommandName.Equals("AlphaPaging"))
        {
            query = "select * from customers where contactname LIKE '" + e.CommandArgument + "%'";
            FillGrid(query);
        }
    }

No comments:

Post a Comment