Show count of results in gridview based on dropdown?
I have a datatable that returns about 30,000 records. I am displaying these entries in an ASP: GridView control. I have a dropdown control where I want the user to be able to select the number of records to display in the GridView. The default should be All, but it can also have values ββlike 20, 50, 100. I'm not really sure how to do this.
What if I don't have paging. Will PageSize work?
I hardcoded GridView.PageSize = 1 and it still returned all entries.
source to share
If you want this PageSize to work for you , set the AllowPaging GridView to true. Obviously, you need to create a method to handle the PageIndexChanging event.
Like this:
protected void myGvw_OnPageIndexChanging(object sender, GridViewPageEventArgs e)
{
myGvw.PageIndex = e.NewPageIndex;
// then recall the method that bind myGvw
}
The DropDown property can be set to AutoPostBack to true, and on its OnSelectedIndexChanged you must set
myGvw.PageSize = Convert.ToInt32(myDropDown.SelectedValue)
source to share
Paging should always be considered as early as possible when selecting data. You don't want to fetch 30,000 records from the database to the application server to show only 50 of them.
Something like: (for page selection 3, 50 per page)
select top 50 from x where pk not in (select top 100 pk from x)
It means that:
CREATE PROCEDURE sspGetItems (@pageSize int, @pageNum int)
AS
SELECT TOP @pageSize
FROM x
WHERE pk NOT IN
(
SELECT TOP (@pageNum - 1) * @pageSize pk FROM x
)
Obviously, when sorting, etc. more attention will be needed.
source to share
Here's what I will do. First, I would add a column to the DataTable that will serve as a counter if it doesn't already exist. Then you bind the GridView to the DataView. Here's some code to demonstrate what I'm talking about:
//add column with counter
table.Columns.Add("counter", typeof(int));
for (int i = 0; i < table.Rows.Count; i++)
{
table.Rows[i]["counter"] = i+1;
}
Then get the default view from the DataTable and set the RowFilter:
DataView view = table.DefaultView;
view.RowFilter = "counter <= 100"; //or whatever number the user selected
Finally, just bind the GridView to the DataView directly.
source to share