GridView Alphabet Paging
By AzamSharp
Views: 11996



Introduction:


GridView paging feature allow us to display fixed number of records on the page and browse to the next page of records. Although paging is a great feature but sometimes we need to view all the items alphabetically. The idea behind this article is to provide a user with a list of all the alphabets and when the user clicks on a certain alphabet then all the records starting with that alphabet will be populated in the GridView control.

Populating the GridView Control:

The first task is to populate the GridView control. I will be using the Northwind database in my article which, is installed by default for SQL SERVER 2000 and SQL SERVER 7 databases. The code below is used to populate the GridView control.  

private void BindData()
    {
        string connectionString = "Server=localhost;Database=Northwind;Trusted_Connection=true";
        SqlConnection myConnection = new SqlConnection(connectionString);
        SqlDataAdapter ad = new SqlDataAdapter("SELECT ProductID, ProductName FROM Products", myConnection);

        DataSet ds = new DataSet();
        ad.Fill(ds);

        gvCategories.DataSource = ds;
        gvCategories.DataBind();
    }


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. Let’s check out the code which is used to create the list.

protected void gvCategories_RowCreated(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.Footer)
        {

            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);

            }
        }
    }


The RowCreated event is used to create the list. In the event first I check for the footer row. Once, the footer row is found I 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 I created LinkButton and set the Text property to the alphabet. Finally, the control is added to the cell collection.

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. Take a look at the RowCommand event below:

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 ProductID, ProductName FROM Products WHERE ProductName 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();
        }
    }


At first I check that if the CommandName is “AlphaPaging”. This check is made since RowCommand handles all the events generated inside the GridView control. Next, I used the T-SQL LIKE operator to fetch the results from the database and populate the results in the GridView control.

Take a look at the image below:



Conclusion:

In this article I demonstrated how you perform paging in the GridView control which is dependent on the alphabets. The code shown above can be optimized by using ASP.NET Caching features and using Custom Entity Classes. 
By AzamSharp


Enter Comment/Feedback
  •  
  •  
  •  
  •  
  •  

Comments/Feedbacks
Subject: Cannot create the footer.
Name: Venu
Date: 3/1/2007 10:57:41 AM
Comment:
Hi, I cannot recreate this solution. I dropped the GridView1 control, then set the showfooter=true. then added the code in this page to populate the footer. But that particular event is not getting fired. Thanks,

Subject: Buttons won't display in footer
Name: Tutu
Date: 3/6/2007 5:31:05 AM
Comment:
The link buttons don't appear in the footer row. I used your code in VB and it worked for the pager row (except the pager disappears when the records are less than the pagesize) but it won't show in the footer.
Subject: Works except
Name: Jon
Date: 4/25/2007 1:30:08 AM
Comment:
Hi,

I tried this and it worked right away (when I showed the footer). The only problem I can see if when there are no rows in the database, it makes the whole grid disappear.

Regards
Jon
Subject: RE: Works Except
Name: AzamSharp
Date: 4/25/2007 8:40:26 AM
Comment:
Hi Jon,

It depends what you want to do if there are no rows present in the database. Some people simply display the message saying "No rows returned". If you still want to create the alphabetical footer then you can assign the GridView to a collection which contains an empty row. This way the GridView will be displayed.

Take a look at this thread:

http://forums.asp.net/thread/1189584.aspx


Subject: events not firing
Name: Phil Peters
Date: 4/27/2007 12:38:04 PM
Comment:
I tried a number of different ways to dynamically add link buttons with the proper CommandName ("Page") and CommandArgument (numbers) for custom paging. No matter where I put them or how, pager row, footer row, using template or without, they never fired the event. The page would post back and the gridview's RowCommand and PageIndexChanging both would be skipped. Why are my dynamically added link buttons not causing events to fire?

Thanks,
Phil
Subject: GridView Alphabet Paging
Name: Jon Paskett
Date: 5/8/2007 6:03:07 PM
Comment:
The other Jon created a VB version that you tested. Do you still have that code? I'm currently using a stored procedure that generates the list and populating a dropdown, this would be much nicer. My list also contains numbers and sometimes special characters. Also in my case, I noticed if I were on page 8 of 15 of letter A and move to letter B, I will be on page 8! Why not page 1? Finally, I would want to put the alphabet links above the gridView. I am sorting thru over 3K records and displaying 20 per page.
Thanks for your help.
Subject: add all buton to the footer
Name: nine
Date: 5/19/2007 4:03:41 AM
Comment:
how to add all button to the footer to dispaly all items
is that by adding new linkbuuton to the footer or do u have other way better than add new link button?
BR
nine
Subject: add all button to the footer
Name: nine
Date: 5/19/2007 4:11:44 AM
Comment:
sorry i've added this code to add all button and it's owrk fine but is that correct way or no?

TableCell cell = e.Row.Cells[0];
cell.ColumnSpan = 2;
LinkButton lb1 = new LinkButton();
lb1.Text = "[all] ";
lb1.CommandArgument = "";
lb1.CommandName = "AlphaPaging";
lb1.Font.Underline = false;
cell.Controls.Add(lb1);
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";
lb.Font.Underline = false;

cell.Controls.Add(lb);
}
Subject: Remove the second cell from the footer
Name: wissam bishouty
Date: 5/23/2007 2:36:45 AM
Comment:
Greetings,

you have to remove the second cell from the footer:
e.Item.Cells.RemoveAt(1)

Subject: Can MS Access do this instead of SQL?
Name: Mizanu
Date: 8/27/2007 6:13:06 PM
Comment:
Hi!
I'm doing the same here, however, my supervisor wants this in MS Access. I had a hard time searching through, finally getting to your page. However, the solution you have is in SQL, do you have a MS Access?
I realised that MS Access does not have SQL's drivers(are they called drivers?) like
"SqlConnection", "SqlDataAdapter", etc...
I'm sorry for asking such a question, but I'm new to asp.net & databases programming.
Hope to get help, thank you so much!
Subject: Alphabetic Sorting - catch postback in page load and set to a variable
Name: jmilton
Date: 8/29/2007 8:45:56 AM
Comment:
This is a great example.

I am building a treeview list of products.

I am using the Alphabetic Control to select the products by the first letter of the product, then display the treeview of the products which expands and shows other properties of the product.

The problem that I am having is catching the EventArgs e in the pageload. I need to set the value to a string and then pass that value to the SQL query.

I am also using MasterPages.

Thanks.
Subject: Event wont fire
Name: Ruben Acon
Date: 1/17/2008 3:15:36 PM
Comment:
I'm having the same issue as "Phil Peters", I can't get the RowCommand event to fire, instead all it does is call the OnPrerender event. My grid is inside an UpdatePanel, I'm not sure if that makes any difference. This is the definition of my grid:










You have no contacts in this contact group.





FYI: I'm assigning the grid's datasource in the OnPreRender event since i don't always need to show it.
Any ideas?
Subject: Event wont fire
Name: Ruben Acon
Date: 1/18/2008 1:39:35 PM
Comment:
Found the solution. All I needed to do was set the EnableViewState property in the grid to true.
Subject: Alphabet paging
Name: hong
Date: 2/4/2008 1:34:20 PM
Comment:
Alphabet paging works, but If I click second(1 2...) on each alphabet, not working, say "pageIndexChanging not handled"?
Subject: Very nice
Name: Arun (The Battle)
Date: 2/14/2008 5:51:47 AM
Comment:
Hi,


It,s Very nice.
and
very helpful to learners,



Thanks,

Mr.India.
Subject: Article seems good
Name: hritha
Date: 2/27/2008 4:03:36 PM
Comment:
Have a doubt.Where can i post doubts/Comments
Subject: RE: Article seems good
Name: AzamSharp
Date: 3/1/2008 7:51:46 AM
Comment:
Hi hritha, You can post the comments right here!
Subject: Not Getting
Name: Rahul
Date: 3/6/2008 4:54:32 AM
Comment:
Hi I m Unable To Implement it can u send me full Program Thanx A lot
Subject: great example. can it created for a data list
Name: geervani
Date: 3/18/2008 9:46:15 PM
Comment:
Hi, Can i create this in a datalist instead of grid view coz i want to display multiple columns
Subject: Problem SelectedIndexChanged event.
Name: Rodrigo
Date: 3/27/2008 7:40:58 AM
Comment:
I worked its sample code and I leave the letters and pagination but the choice of a cell I chose the correct page when registration with the letters but if they choose when pages with numbers.
Which is this?
This is my code:

Protected void gv_import_SelectedIndexChanged (object sender, EventArgs e)
(
GridViewRow Row = gv_import.SelectedRow;
Txt_nombre.Text = row.Cells [1]. Text;
Txt_id.Text = row.Cells [0]. Text;
Gv_import.Visible = false;


)

Thanks.
Subject: RowCommand event not firing
Name: purple_chicken
Date: 4/21/2008 2:22:23 AM
Comment:
I have tried using the sample code but no matter what I try the RowCommand event will not fire when you click on the relevant letter. I am using an Access db but can't see that it will make a difference as the initial load brings up all the records before sorting.
I have enableviewstate set to true.
help plse it's driving me mad!"!
rgds
Subject: rowcommand event and alphabet paging
Name: purple_chicken
Date: 4/21/2008 3:46:19 PM
Comment:
I GOT IT!!
I eventually realised that i had the page stored in a content placeholder of a masterpage which funny old thing the placeholders "enableviewstate" was set to false. one swift set to true and all my troubles were gone.



Join WebHost4Life.com






Copyright GridViewGuy 2007-2008