Sunday, December 21, 2008

How to implement paging in Silver Light2 DataGrid

Introduction

Silver light2 is one of the most new and exciting technology from Microsoft. As my company has decided to develop application by using Silver Ligth2 that’s why I am exploring the silver light2 controls. When I started to work with Silver Light2 Datagrid control, I saw there is no built-in paging facility. The paging facility is extremely necessary to our application. Silver light2 is still Beta1. So I am expecting these sorts of features will be added to the release version. Nevertheless I tried to develop a user control which shows you how paging can be implemented in DataGrid.

Using the code

In order to implement paging in DataGrid, I used RowDetailsTemplate property of the DataGrid. This RowDetailsTemplate gets or sets the template that is used to display the content of the details section of rows. This property is visible at the last row of the DataGrid where I put the navigation buttons. To visible the RowDetailsTemplate property for the last row, DataGrid subscribes the PreparingRow event.

private void grdPaging_PreparingRow(object sender, DataGridRowEventArgs e)
{
//_countrow is the current preparing row number, totalRowsInGrid is the total row in
// grid.
//totalRowsInGrid can be equal to or less then chunk size

if (_countrow == totalRowsInGrid)
{
e.Row.DetailsVisibility = Visibility.Visible;
}
_countrow++;
}

To put the navigation buttons, DataGrid subscribes the PreparingRowDetails event. Here I used a stackpanel to house all the navigation buttons.

private void grdPaging_PreparingRowDetails(object sender, DataGridRowDetailsEventArgs e)
{
//Get the stackPanel from the RowDetailsTemplate
StackPanel stk = e.DetailsElement.FindName("stk") as StackPanel;
if (stk != null)
{
stk.Children.Clear();
int totalpage = Convert.ToInt32(Math.Ceiling(this.TotalRow/(double) this.ChunkSize));
for (int i = _currentPage; i <= totalpage; i++)
{
Button btn = new Button();
btn.Width = 20;
btn.Content = i;
btn.Click += new RoutedEventHandler(btn_Click);
btn.Margin = new Thickness(3);
stk.Children.Add(btn);
}
}
}
As you will see in the source code, the rest of the statements are very typical to implement paging in DataGrid.