C# Tutorials and offshore development in India
    Tutorials   Resources   Forum   Communities   Interview   Jobs   Projects   Offshore Development    
Silverlight Tutorials | Mentor | Code Converter | Articles | Code Factory | Computer Jokes | Members | Peer Appraisal | IT Companies | Bookmarks | Revenue Sharing |


Prizes & Awards
My Profile



Active Members
TodayLast 7 Days more...

New Feature: Community Sites: Create your own .NET community website and start earning from Google AdSense ! It's Free !






Paging and Sorting a GridView in XAML


Posted Date: 09 Jul 2008    Resource Type: Code Snippets    Category: DataGridView
Author: siddharthMember Level: Bronze    
Rating: Points: 10



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>










Responses


No responses found. Be the first to respond and make money from revenue sharing program.

Feedbacks      
Popular Tags   What are tags ?   Search Tags  
Sorting in GridView control  .  Sorting a GridView control in XAML  .  Paging with GridView control  .  Paging with GridView  .  Paging and Sorting in GridView control  .  Paging and Sorting a GridView in XAML  .  Paging a GrridView  .  Paging a GridView control in XAML  .  Paging  .  

Post Feedback


This is a strictly moderated forum. Only approved messages will appear in the site. Please use 'Spell Check' in Google toolbar before you submit.
You must Sign In to post a response.
Next Resource: Obtaining Checkbox's SelectedItem
Previous Resource: conversion of datagrid view to excel format
Return to Discussion Resource Index
Post New Resource
Category: DataGridView


Post resources and earn money!
 
Related Resources



dotNet Slackers   BizTalk Adaptors    Web Design


Contact Us    Privacy Policy    Terms Of Use