Friday, March 28, 2008

Alphabetical Paging in a Gridview control

protected void gvCategories_RowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Pager)
{
TableCell cell = e.Row.Cells[0];
cell.ColumnSpan = 2;
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);
}
}
}
protected void gvCategories_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName.Equals("AlphaPaging"))
{
string connectionString = "Server=localhost;Database=Northwind;Trusted_Connection=true";
string selectQuery = "SELECT CategoryID, CategoryName FROM Categories WHERE CategoryName LIKE '" + e.CommandArgument + "%'";
SqlConnection myConnection = new SqlConnection(connectionString);
SqlDataAdapter ad = new SqlDataAdapter(selectQuery,myConnection);
DataSet ds = new DataSet();
ad.Fill(ds);
gvCategories.DataSource = ds;
gvCategories.DataBind();
}
}