Paging and Sorting a GridView in XAML

The sample code consists of C# code followed by XAML code to perform paging and sorting data in a GridView control. The C# code is follows immediately


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Data.SqlClient;
using System.Data;
using System.ComponentModel;
using System.Configuration;
using System.Xml;

namespace WpfApplication1_grid
{
/// <summary>
/// Interaction logic for Window1.xaml
/// </summary>
public partial class Window1 : Window
{
DataSet ds = new DataSet();
//For holding the data globally.
DataTable dt_Products = new DataTable("student");
//For storing the current page number.
private int paging_PageIndex = 1;
//For storing the Paging Size. Here it is static but you can use a property
//to expose and update value.
private int paging_NoOfRecPerPage = 2;

//To check the paging direction according to use selection.
private enum PagingMode { First = 1, Next = 2, Previous = 3, Last = 4 };

public Window1()
{
InitializeComponent();
lstView.MouseDoubleClick = new MouseButtonEventHandler(lstVi ew_MouseDoubleClick);
lstView.MouseLeftButtonUp = new MouseButtonEventHandler(lstVi ew_MouseLeftButtonUp);
lstView.MouseDown = new MouseButtonEventHandler(lstVi ew_MouseDown);

}

void lstView_MouseDown(object sender, MouseButtonEventArgs e)
{
//MessageBox.Show("Hi");
}

void lstView_MouseLeftButtonUp(obj ect sender, MouseButtonEventArgs e)
{
//MessageBox.Show("Hi");

}

void lstView_MouseDoubleClick(obje ct sender, MouseButtonEventArgs e)
{
//MessageBox.Show("Hi");


DependencyObject dep = (DependencyObject)e.OriginalS ource;
while ((dep != null) && !(dep is ListViewItem))
{ dep = VisualTreeHelper.GetParent(de p); }
if (dep == null)
return;
DataRowView item = (DataRowView)lstView.ItemCont ainerGenerator.ItemFromContai ner(dep);

System.Data.DataRowView value = (System.Data.DataRowView)lstV iew.SelectedItem;

string lstValue = "";
//System.Windows.Controls.Lis tBoxItem curItem = ((System.Windows.Controls.Lis tBoxItem)lstView.SelectedItem );
lstValue = value.Row["rollno"].ToString();

MessageBox.Show("you selected " lstValue);

//MessageBox.Show("item " item[1]);

// Do something with the item...
}

GridViewColumnHeader _lastHeaderClicked = null;
ListSortDirection _lastDirection = ListSortDirection.Ascending;

private void Sort(string sortBy, ListSortDirection direction)
{
ICollectionView dataView =
CollectionViewSource.GetDefau ltView(lstView.ItemsSource);

dataView.SortDescriptions.Cle ar();
SortDescription sd = new SortDescription(sortBy, direction);
dataView.SortDescriptions.Add (sd);
dataView.Refresh();
}

void GridViewColumnHeaderClickedHa ndler(object sender,
RoutedEventArgs e)
{
GridViewColumnHeader headerClicked =
e.OriginalSource as GridViewColumnHeader;
ListSortDirection direction;

if (headerClicked != null)
{
if (headerClicked.Role != GridViewColumnHeaderRole.Padd ing)
{
if (headerClicked != _lastHeaderClicked)
{
direction = ListSortDirection.Ascending;
}
else
{
if (_lastDirection == ListSortDirection.Ascending)
{
direction = ListSortDirection.Descending;
}
else
{
direction = ListSortDirection.Ascending;
}
}

string header = headerClicked.Column.Header as string;
Sort(header, direction);

if (direction == ListSortDirection.Ascending)
{
headerClicked.Column.HeaderTe mplate =
Resources["HeaderTemplateArrowUp"] as DataTemplate;
}
else
{
headerClicked.Column.HeaderTe mplate =
Resources["HeaderTemplateArrowDown"] as DataTemplate;
}

// Remove arrow from previously sorted header
if (_lastHeaderClicked != null && _lastHeaderClicked != headerClicked)
{
_lastHeaderClicked.Column.Hea derTemplate = null;
}


_lastHeaderClicked = headerClicked;
_lastDirection = direction;
}
}
}

private void Grid_Loaded()
{
//DataSet dsGrid = new DataSet();
//dsGrid = this.GetDataset();
SqlConnection con = new SqlConnection("Data source=cp960sw;initial catalog=vh-enh-poc;uid=sa;pas sword=rmsindia;");
SqlCommand cmd = new SqlCommand("select * from student", con);
SqlDataAdapter sqlDa = new SqlDataAdapter();
sqlDa.SelectCommand = cmd;
sqlDa.Fill(ds);
//return ds;
lstView.DataContext = ds.Tables[0].DefaultView;

}

private void Window_Loaded(object sender, RoutedEventArgs e)
{
// Grid_Loaded();
ListProducts();
}

private void button1_Click(object sender, RoutedEventArgs e)
{
System.Data.DataRowView[] value = new System.Data.DataRowView[lstView.SelectedItems.Count];
for(int i=0;i<lstView.SelectedItems.C ount;i )
{
string lstValue = "";
value = (System.Data.DataRowView)lstView.SelectedItems;
lstValue = value.Row["firstname"].ToString() " " value.Row["lastname"].ToString();
MessageBox.Show("you selected " lstValue);
}
}

private void btnFirst_Click(object sender, RoutedEventArgs e)
{
CustomPaging((int)PagingMode. First);
}

private void btnNext_Click(object sender, RoutedEventArgs e)
{
CustomPaging((int)PagingMode. Next);
}

private void btnPrev_Click(object sender, RoutedEventArgs e)
{
CustomPaging((int)PagingMode. Previous);
}

private void btnLast_Click(object sender, RoutedEventArgs e)
{
CustomPaging((int)PagingMode. Last);
}

private void ListProducts()
{
SqlConnection sqlCon = new SqlConnection();
sqlCon.ConnectionString = "Data Source=cp960sw;Initial catalog=vh-enh-poc;uid=sa;pas sword=rmsindia;";

SqlCommand cmd = new SqlCommand();
cmd.Connection = sqlCon;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT * FROM student";

SqlDataAdapter sqlDa = new SqlDataAdapter();
sqlDa.SelectCommand = cmd;

try
{
paging_PageIndex = 1;//For default
sqlDa.Fill(dt_Products);

if (dt_Products.Rows.Count > 0)
{
DataTable tmpTable = new DataTable();

//Copying the schema to the temporary table.
tmpTable = dt_Products.Clone();

//If total record count is greater than page size then
//import records from 0 to pagesize (here 20)
//Else import reports from 0 to total record count.
if (dt_Products.Rows.Count >= paging_NoOfRecPerPage)
{
for (int i = 0; i < paging_NoOfRecPerPage; i )
{
tmpTable.ImportRow(dt_Products.Rows);
}
}
else
{
for (int i = 0; i < dt_Products.Rows.Count; i )
{
tmpTable.ImportRow(dt_Products.Rows);
}
}

//Bind the table to the gridview.
lstView.DataContext = tmpTable.DefaultView;

//Dispose the temporary table.
tmpTable.Dispose();
}
else
{
MessageBox.Show("Message");
}
}
catch (Exception ex)
{
MessageBox.Show("Error Message");
}
finally
{
sqlDa.Dispose();
cmd.Dispose();
sqlCon.Dispose();
}
}

private void CustomPaging(int mode)
{
//There is no need for these variables but i created them just for readability
int totalRecords = dt_Products.Rows.Count;
int pageSize = paging_NoOfRecPerPage;

//If total record count is less than the page size then return.
if (totalRecords <= pageSize)
{
return;
}

switch (mode)
{
case (int)PagingMode.Next:
if (totalRecords > (paging_PageIndex * pageSize))
{
DataTable tmpTable = new DataTable();
tmpTable = dt_Products.Clone();

if (totalRecords >= ((paging_PageIndex * pageSize) pageSize))
{
for (int i = paging_PageIndex * pageSize;
i < ((paging_PageIndex * pageSize) pageSize); i )
{
tmpTable.ImportRow(dt_Products.Rows);
}
}
else
{
for (int i = paging_PageIndex * pageSize; i < totalRecords; i )
{
tmpTable.ImportRow(dt_Products.Rows);
}
}

paging_PageIndex = 1;

lstView.DataContext = tmpTable.DefaultView;
tmpTable.Dispose();
}
break;
case (int)PagingMode.Previous:
if (paging_PageIndex > 1)
{
DataTable tmpTable = new DataTable();
tmpTable = dt_Products.Clone();

paging_PageIndex -= 1;

for (int i = ((paging_PageIndex * pageSize) - pageSize);
i < (paging_PageIndex * pageSize); i )
{
tmpTable.ImportRow(dt_Products.Rows);
}
lstView.DataContext = tmpTable.DefaultView;
tmpTable.Dispose();
}
break;
case (int)PagingMode.First:
paging_PageIndex = 2;
CustomPaging((int)PagingMode. Previous);
break;
case (int)PagingMode.Last:
paging_PageIndex = (totalRecords/pageSize);
CustomPaging((int)PagingMode. Next);
break;
}
DisplayPagingInfo();
}

private void DisplayPagingInfo()
{
//There is no need for these variables but i created them just for readability
int totalRecords = dt_Products.Rows.Count;
int pageSize = paging_NoOfRecPerPage;

string pagingInfo = "Displaying " (((paging_PageIndex-1)*pageSi ze) 1)
" to " paging_PageIndex*pageSize;

if (dt_Products.Rows.Count < (paging_PageIndex * pageSize))
{
pagingInfo = "Displaying " (((paging_PageIndex - 1) * pageSize) 1)
" to " totalRecords;
}
lblPagingInfo.Content = pagingInfo;
lblPageNumber.Content = paging_PageIndex;
}
}
}





XAML code for sorting,paging and adding checkbox to listview (gridview) :


<Window x:Class="WpfApplication1_grid .Window1"
Really Long Link
Really Long Link
Title="Window1" Height="300" Width="667" Loaded="Window_Loaded">
<Window.Resources>
<ataTemplate x:Key="FirstCell">
<StackPanel Orientation="Horizontal">
<CheckBox Name="chk1" IsChecked="{Binding Path=IsSelected,
RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ListViewItem}}}"/>
</StackPanel>
</DataTemplate>
</Window.Resources>
<Grid>
<ListView ItemsSource="{Binding}" Name="lstView" GridViewColumnHeader.Click="G ridViewColumnHeaderClickedHan dler">
<ListView.View>
<GridView>
<GridView.Columns>
<GridViewColumn Header="" CellTemplate="{StaticResource FirstCell}"
Width="30"/>

<GridViewColumn Header="Rollno" DisplayMemberBinding="{Binding Path=rollno}"/>
<GridViewColumn Header="FirstName" DisplayMemberBinding="{Binding Path=firstname}"/>
<GridViewColumn Header="LastName" DisplayMemberBinding="{Binding Path=lastname}"/>
<GridViewColumn Header="DOJ" DisplayMemberBinding="{Binding Path=DOJ}"/>

</GridView.Columns>
</GridView>
</ListView.View>
</ListView>
<Button Height="23" HorizontalAlignment="Left" Margin="18,0,0,22"
Name="btnFirst" VerticalAlignment="Bottom" Width="40" Content="<<"
Click="btnFirst_Click" Opacity="0.75">
</Button>
<Button Height="23" HorizontalAlignment="Right" Margin="0,0,474,22"
Name="btnNext" VerticalAlignment="Bottom" Width="40" Content=">"
Click="btnNext_Click" Opacity="0.75">
</Button>
<Button Height="23" HorizontalAlignment="Right" Margin="0,0,429,22"
VerticalAlignment="Bottom" Width="40" Name="btnLast"
Click="btnLast_Click" Opacity="0.75" Content=">>">
</Button>
<Button Height="23" Margin="62,0,551,22" VerticalAlignment="Bottom"
Name="btnPrev" Click="btnPrev_Click" Opacity="0.75" Content="<">
</Button>

<Label Height="23.277" HorizontalAlignment="Left" Margin="14.37,89.723,0,0"
Name="lblPagingInfo" VerticalAlignment="Top" Width="282.63"/>
<Label Height="23.277" HorizontalAlignment="Left" Margin="108.37,0,0,23"
Name="lblPageNumber" VerticalAlignment="Bottom" Width="26.63" Content="1"/>

<Button Height="23" Margin="18,0,0,107" Name="button1" VerticalAlignment="Bottom" HorizontalAlignment="Left" Width="75" Click="button1_Click">Button< /Button>
</Grid>
</Window>


Comments

Author: Phagu Mahato21 Feb 2014 Member Level: Gold   Points : 10

You can try this code snippet


namespace WPFApp
{
public partial class MainWindow : Window, INotifyPropertyChanged
{
private DataGridColumn currentSortColumn;

private ListSortDirection currentSortDirection;

public MainWindow()
{
InitializeComponent();
DataContext = this;
RefreshProducts();
}

private void ProductsDataGrid_Loaded(object sender, RoutedEventArgs e)
{
DataGrid dataGrid = (DataGrid)sender;

currentSortColumn = dataGrid.Columns.Where(c => c.SortDirection.HasValue).Single();
currentSortDirection = currentSortColumn.SortDirection.Value;
}

private void ProductsDataGrid_TargetUpdated(object sender, DataTransferEventArgs e)
{
if (currentSortColumn != null)
{
currentSortColumn.SortDirection = currentSortDirection;
}
}

private void ProductsDataGrid_Sorting(object sender, DataGridSortingEventArgs e)
{
e.Handled = true;
string sortField = String.Empty;


switch (e.Column.SortMemberPath)
{
case ("Id"):
sortField = "Id";
break;
case ("Name") :
sortField = "Name";
break;
}

ListSortDirection direction = (e.Column.SortDirection != ListSortDirection.Ascending) ?
ListSortDirection.Ascending : ListSortDirection.Descending;
bool sortAscending = direction == ListSortDirection.Ascending;
Sort(sortField, sortAscending);
currentSortColumn.SortDirection = null;
e.Column.SortDirection = direction;
currentSortColumn = e.Column;
currentSortDirection = direction;
}

public event PropertyChangedEventHandler PropertyChanged;

private ObservableCollection products;
private int start = 0;
private int itemCount = 5;
private string sortColumn = "Id";
private bool ascending = true;
private int totalItems = 0;
private ICommand firstCommand;
private ICommand previousCommand;
private ICommand nextCommand;
private ICommand lastCommand;

public ObservableCollection Products
{
get
{
return products;
}
private set
{
if (object.ReferenceEquals(products, value) != true)
{
products = value;
NotifyPropertyChanged("Products");
}
}
}

public ICommand FirstCommand
{
get
{
if (firstCommand == null)
{
firstCommand = new RelayCommand
(
param =>
{
start = 0;
RefreshProducts();
},
param =>
{
return start - itemCount >= 0 ? true : false;
}
);
}

return firstCommand;
}
}



  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: