Read + Write + Report
Home | Start a blog | About Orble | FAQ | Sites | Writers | Advertise | My Orble | Login

Paging in GridView

June 2nd 2008 05:19
C# code for paging,sorting data in gridview

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[i] = (System.Data.DataRowView)lstView.SelectedItems[i];
lstValue = value[i].Row["firstname"].ToString() " " value[i].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[i]);
}
}
else
{
for (int i = 0; i < dt_Products.Rows.Count; i )
{
tmpTable.ImportRow(dt_Products.Rows[i]);
}
}

//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[i]);
}
}
else
{
for (int i = paging_PageIndex * pageSize; i < totalRecords; i )
{
tmpTable.ImportRow(dt_Products.Rows[i]);
}
}

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[i]);
}

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="&lt;&lt;"
Click="btnFirst_Click" Opacity="0.75">
</Button>
<Button Height="23" HorizontalAlignment="Right" Margin="0,0,474,22"
Name="btnNext" VerticalAlignment="Bottom" Width="40" Content="&gt;"
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="&gt;&gt;">
</Button>
<Button Height="23" Margin="62,0,551,22" VerticalAlignment="Bottom"
Name="btnPrev" Click="btnPrev_Click" Opacity="0.75" Content="&lt;">
</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>
33
Vote


   
Subscribe to this blog 


Just this blog This blog and DailyOrble (recommended)

   

   


Add A Comment

To create a fully formatted comment please click here.


CLICK HERE TO LOGIN | CLICK HERE TO REGISTER

Name or Orble Tag
Home Page (optional)
Comments
Bold Italic Underline Strikethrough Separator Left Center Right Separator Quote Insert Link Insert Email
Notify me of replies
Notify extra people about this comment
Is this a private comment?
List the Email Addresses or Orble Tags of the people you would like to be notified about this comment


One per line max of 30

List the Email Addresses or Orble Tags of the people you would like to be notified about this private comment thread. Only the people in this list will be able to see or reply to your comment.


One per line max of 30

Your Name
(for the email going out to the above list, it can be different to your Orble Tag)
Your Email Address
(optional)
(required for reply notification)
Submit
More Posts
3 Posts
2 Posts
5 Posts dating from May 2008
Email Subscription
Receive e-mail notifications of new posts on this blog:
0

Siddharth sood's Blogs

35 Vote(s)
0 Comment(s)
1 Post(s)
76 Vote(s)
0 Comment(s)
2 Post(s)
36 Vote(s)
0 Comment(s)
1 Post(s)
48 Vote(s)
0 Comment(s)
1 Post(s)
28 Vote(s)
0 Comment(s)
1 Post(s)
69 Vote(s)
0 Comment(s)
2 Post(s)
155 Vote(s)
0 Comment(s)
4 Post(s)
4123 Vote(s)
13 Comment(s)
77 Post(s)
24 Vote(s)
0 Comment(s)
1 Post(s)
23 Vote(s)
0 Comment(s)
1 Post(s)
Moderated by Siddharth sood
Copyright © 2006 2007 2008 On Topic Media PTY LTD. All Rights Reserved. Design by Vimu.com.
On Topic Media ZPages: Sydney |  Melbourne |  Brisbane |  London |  Birmingham |  Leeds     [ Advertise ] [ Contact Us ] [ Privacy Policy ]