473,382 Members | 1,359 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,382 software developers and data experts.

ASP.NET Datagrid sorting

I want my gird to sort only the items on the current page when I click on a column header. I wrote a little test app, but when I sort it pulls in items from other pages and places them on the current page.
i.e.

If I have:

IntegerValue StringValue CurrencyValue
0 Item 0 0
1 Item 1 1.23
< >
then sort I will get:
IntegerValue StringValue CurrencyValue
8 Item 8 9.84
7 Item 7 8.61
< >
and what I want is:

IntegerValue StringValue CurrencyValue
1 Item 1 1.23
0 Item 0 0
< >

using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;

namespace WebApplication2
{
/// <summary>
/// Summary description for WebForm1.
/// </summary>
public class WebForm1 : System.Web.UI.Page
{
protected System.Web.UI.WebControls.DataGrid ItemsGrid;

private void Page_Load(object sender, System.EventArgs e)
{
ItemsGrid.DataSource = CreateDataSource();
ItemsGrid.DataBind();

}
ICollection CreateDataSource()
{

// Create a Random object to mix up the order of items in the
// sample data.
Random Rand_Num = new Random();

// Create sample data for the DataGrid control.
DataTable dt = new DataTable();
DataRow dr;

// Define the columns of the table.
dt.Columns.Add(new DataColumn("IntegerValue", typeof(Int32)));
dt.Columns.Add(new DataColumn("StringValue", typeof(String)));
dt.Columns.Add(new DataColumn("CurrencyValue", typeof(Double)));

// Populate the table with sample values.
for (int i=0; i<=8; i++)
{

dr = dt.NewRow();

dr[0] = i;
dr[1] = "Item " + i.ToString();
dr[2] = 1.23 * i;

dt.Rows.Add(dr);

}

// To persist the data source between posts to the server,
// store it in session state.
Session["Source"] = dt;

DataView dv = new DataView(dt);

return dv;

}
#region Web Form Designer generated code
override protected void OnInit(EventArgs e)
{
//
// CODEGEN: This call is required by the ASP.NET Web Form Designer.
//
InitializeComponent();
base.OnInit(e);
}

/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.ItemsGrid.PageIndexChanged += new System.Web.UI.WebControls.DataGridPageChangedEvent Handler(this.ItemsGrid_PageIndexChanged);
this.ItemsGrid.SortCommand += new System.Web.UI.WebControls.DataGridSortCommandEvent Handler(this.ItemsGrid_SortCommand);
this.Load += new System.EventHandler(this.Page_Load);

}
#endregion

private void ItemsGrid_SortCommand(object source, System.Web.UI.WebControls.DataGridSortCommandEvent Args e)
{

// Retrieve the data source from session state.
DataTable dt = (DataTable)Session["Source"];

// Create a DataView from the DataTable.
DataView dv = new DataView(dt);

// The DataView provides an easy way to sort. Simply set the
// Sort property with the name of the field to sort by.

if(Session["sort"] == "ASC")
{
dv.Sort = e.SortExpression + " ASC";
Session["sort"] = "DESC";
}
else
{
dv.Sort = e.SortExpression + " DESC";
Session["sort"] = "ASC";
}

// Re-bind the data source and specify that it should be sorted
// by the field specified in the SortExpression property.
ItemsGrid.DataSource = dv;
ItemsGrid.DataBind();

}

private void ItemsGrid_PageIndexChanged(object source, System.Web.UI.WebControls.DataGridPageChangedEvent Args e)
{
// For the DataGrid control to navigate to the correct page when
// paging is allowed, the CurrentPageIndex property must be updated
// programmatically. This process is usually accomplished in the
// event-handling method for the PageIndexChanged event.

// Set CurrentPageIndex to the page the user clicked.
ItemsGrid.CurrentPageIndex = e.NewPageIndex;

// Rebind the data to refresh the DataGrid control.
ItemsGrid.DataSource = CreateDataSource();
ItemsGrid.DataBind();

}

}
}



<%@ Page language="c#" Codebehind="WebForm1.aspx.cs" AutoEventWireup="false" Inherits="WebApplication2.WebForm1" %>
<!doctype html public "-//w3c//dtd html 4.0 transitional//en" >
<html>
<head>
<title>WebForm1</title>
<meta name="GENERATOR" content="Microsoft Visual Studio .NET 7.1">
<meta name="CODE_LANGUAGE" content="C#">
<meta name="vs_defaultClientScript" content="JavaScript">
<meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5">
</head>
<body ms_positioning="GridLayout">
<form id="Form1" method="post" runat="server">
<asp:datagrid id="ItemsGrid" style="Z-INDEX: 101; LEFT: 104px; POSITION: absolute; TOP: 208px"
runat="server" allowsorting="True" allowpaging="True" pagesize="2"></asp:datagrid>
</form>
</body>
</html>
Nov 18 '05 #1
1 2318
I think for this type of sorting, you can do client side sorting. Check out
this article,
http://msdn.microsoft.com/msdnmag/is...e/default.aspx

Other option is to have custom paging in your datagrid, get the first page
data alone in your datasource and then bind it to your datagrid. For
implementing custom paging, check out this article,
http://www.microsoft.com/india/msdn/...ebServerContro
l.aspx

--
Saravana
Microsoft MVP - ASP.NET
www.extremeexperts.com

"Jeremy" <Je****@discussions.microsoft.com> wrote in message
news:B7**********************************@microsof t.com...
I want my gird to sort only the items on the current page when I click on a column header. I wrote a little test app, but when I sort it pulls in
items from other pages and places them on the current page.

i.e.

If I have:

IntegerValue StringValue CurrencyValue
0 Item 0 0
1 Item 1 1.23
< >
then sort I will get:
IntegerValue StringValue CurrencyValue
8 Item 8 9.84
7 Item 7 8.61
< >
and what I want is:

IntegerValue StringValue CurrencyValue
1 Item 1 1.23
0 Item 0 0
< >

using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;

namespace WebApplication2
{
/// <summary>
/// Summary description for WebForm1.
/// </summary>
public class WebForm1 : System.Web.UI.Page
{
protected System.Web.UI.WebControls.DataGrid ItemsGrid;

private void Page_Load(object sender, System.EventArgs e)
{
ItemsGrid.DataSource = CreateDataSource();
ItemsGrid.DataBind();

}
ICollection CreateDataSource()
{

// Create a Random object to mix up the order of items in the // sample data.
Random Rand_Num = new Random();

// Create sample data for the DataGrid control.
DataTable dt = new DataTable();
DataRow dr;

// Define the columns of the table.
dt.Columns.Add(new DataColumn("IntegerValue", typeof(Int32))); dt.Columns.Add(new DataColumn("StringValue", typeof(String))); dt.Columns.Add(new DataColumn("CurrencyValue", typeof(Double)));
// Populate the table with sample values.
for (int i=0; i<=8; i++)
{

dr = dt.NewRow();

dr[0] = i;
dr[1] = "Item " + i.ToString();
dr[2] = 1.23 * i;

dt.Rows.Add(dr);

}

// To persist the data source between posts to the server,
// store it in session state.
Session["Source"] = dt;

DataView dv = new DataView(dt);

return dv;

}
#region Web Form Designer generated code
override protected void OnInit(EventArgs e)
{
//
// CODEGEN: This call is required by the ASP.NET Web Form Designer. //
InitializeComponent();
base.OnInit(e);
}

/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.ItemsGrid.PageIndexChanged += new System.Web.UI.WebControls.DataGridPageChangedEvent Handler(this.ItemsGrid_Pag
eIndexChanged); this.ItemsGrid.SortCommand += new System.Web.UI.WebControls.DataGridSortCommandEvent Handler(this.ItemsGrid_Sor
tCommand); this.Load += new System.EventHandler(this.Page_Load);

}
#endregion

private void ItemsGrid_SortCommand(object source, System.Web.UI.WebControls.DataGridSortCommandEvent Args e) {

// Retrieve the data source from session state.
DataTable dt = (DataTable)Session["Source"];

// Create a DataView from the DataTable.
DataView dv = new DataView(dt);

// The DataView provides an easy way to sort. Simply set the // Sort property with the name of the field to sort by.

if(Session["sort"] == "ASC")
{
dv.Sort = e.SortExpression + " ASC";
Session["sort"] = "DESC";
}
else
{
dv.Sort = e.SortExpression + " DESC";
Session["sort"] = "ASC";
}

// Re-bind the data source and specify that it should be sorted // by the field specified in the SortExpression property.
ItemsGrid.DataSource = dv;
ItemsGrid.DataBind();

}

private void ItemsGrid_PageIndexChanged(object source, System.Web.UI.WebControls.DataGridPageChangedEvent Args e) {
// For the DataGrid control to navigate to the correct page when // paging is allowed, the CurrentPageIndex property must be updated // programmatically. This process is usually accomplished in the // event-handling method for the PageIndexChanged event.

// Set CurrentPageIndex to the page the user clicked.
ItemsGrid.CurrentPageIndex = e.NewPageIndex;

// Rebind the data to refresh the DataGrid control.
ItemsGrid.DataSource = CreateDataSource();
ItemsGrid.DataBind();

}

}
}



<%@ Page language="c#" Codebehind="WebForm1.aspx.cs" AutoEventWireup="false" Inherits="WebApplication2.WebForm1" %> <!doctype html public "-//w3c//dtd html 4.0 transitional//en" >
<html>
<head>
<title>WebForm1</title>
<meta name="GENERATOR" content="Microsoft Visual Studio .NET 7.1">
<meta name="CODE_LANGUAGE" content="C#">
<meta name="vs_defaultClientScript" content="JavaScript">
<meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5"> </head>
<body ms_positioning="GridLayout">
<form id="Form1" method="post" runat="server">
<asp:datagrid id="ItemsGrid" style="Z-INDEX: 101; LEFT: 104px; POSITION: absolute; TOP: 208px" runat="server" allowsorting="True" allowpaging="True" pagesize="2"></asp:datagrid> </form>
</body>
</html>

Nov 18 '05 #2

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
by: Chris Mayers | last post by:
I have a Windows Forms DataGrid that has a DataView as a datasource. My problem is that I want the datagrid to exhibit some special sorting properties when the header rows are clicked on. From...
2
by: DelphiBlue | last post by:
I have a Nested Datagrid that is using a data relations to tie the parent child datagrids together. All is working well with the display but I am having some issues trying to sort the child...
1
by: Sargas Atum | last post by:
Hi all, 1. I have a problem with cell selection in a table in a DataGrid. I dont want that anybody writes in the cells. That was not a problem I changed them to "read only", but if I am going...
3
by: melanieab | last post by:
Hi, I'm programatically sorting in a datagrid. When a column header is clicked, the sort happens twice for some reason, making it looks like it only sorts in descending order. I can tell it...
7
by: DC Gringo | last post by:
I have a datagrid that won't sort. The event handler is firing and return label text, just not the sort. Here's my Sub Page_Load and Sub DataGrid1_SortCommand: -------------------- Private...
4
by: Manny Chohan | last post by:
hi guys, my code is returning an array and i need to create datagrid so that i can have sorting and implement prev....next function on it to navigate. is there any way this can be done in...
5
by: DKC | last post by:
Hi, Using VB.NET. I have a datagrid having a strongly typed array of objects as its data source. The data from the array of objects is displayed by means of a table style, which is fine, but...
1
by: ECD | last post by:
Hello all, I can usually find solutions to my .NET problems by searching these groups, but I'm stumped on this one. I have a datagrid in VB.NET (2.0 framework). I want to disable sorting on...
0
by: rupalirane07 | last post by:
Both grids displays fine. But the problem is only parent datagrid sorting works fine but when i clik on child datagrid for sorting it gives me error: NullReferenceException error Any...
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.