The
Problem:
You have a multi page datagrid and you want to
display and highlight the selected row which has been set programmatically. The
datagrid doesn’t have built in functionality which you can use to determine on
which page the row with the selectedIndex is.
Solution:
I have a datagrid on my page, dgPaging, and
AllowPaging = True and the PageSize = 5.
In Page_Load I load the datagrid with data that I get
from SQL. I also use the following to store the count of the items in the
dataset, because when you use dgPaging.Items.Count it will give you the amount to which you set the
PageSize.
Session["itemCount"] =
ds.Tables[0].Rows.Count;
To get the page on which the row with the
selectedIndex is on, use the following:
private Int32 GetPage(int selectIndex)
{
//Get the count of items in the
datagrid
int itemCount =
Int32.Parse(Session["itemCount"].ToString());
int pageSize = dgPaging.PageSize;
//The cnt is the same as the
pageIndex
int cnt = 0;
//Increment with the
pageSize
for(int i=cnt;i <
itemCount; i=i+pageSize)
{
if((selectIndex > i) &&
(selectIndex < (i + pageSize)))
{
return cnt;
}
cnt++;
}
return 0;
}
Then call it and pass the
SelectedIndex:
dgPaging.CurrentPageIndex =
GetPage(dgPaging.SelectedIndex);
The problem here is that as soon as you move to
another page on a datagrid, the index of the first item on the new page is 0.
E.g. if the SelectedIndex of your item was 8, and your PageSize is set to 5,
then on the 2nd page where 8 would appear, its Index will be 3. To
overcome this, you just do the following:
dgPaging.SelectedIndex = dgPaging.SelectedIndex -
(dgPaging.PageSize * dgPaging.CurrentPageIndex);
Let me know if I
missed something - maybe an easier way :)
powered by IMHO