472,988 Members | 2,845 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 472,988 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 2277
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: lllomh | last post by:
Define the method first this.state = { buttonBackgroundColor: 'green', isBlinking: false, // A new status is added to identify whether the button is blinking or not } autoStart=()=>{
0
tracyyun
by: tracyyun | last post by:
Hello everyone, I have a question and would like some advice on network connectivity. I have one computer connected to my router via WiFi, but I have two other computers that I want to be able to...
4
NeoPa
by: NeoPa | last post by:
Hello everyone. I find myself stuck trying to find the VBA way to get Access to create a PDF of the currently-selected (and open) object (Form or Report). I know it can be done by selecting :...
3
NeoPa
by: NeoPa | last post by:
Introduction For this article I'll be using a very simple database which has Form (clsForm) & Report (clsReport) classes that simply handle making the calling Form invisible until the Form, or all...
3
by: nia12 | last post by:
Hi there, I am very new to Access so apologies if any of this is obvious/not clear. I am creating a data collection tool for health care employees to complete. It consists of a number of...
0
NeoPa
by: NeoPa | last post by:
Introduction For this article I'll be focusing on the Report (clsReport) class. This simply handles making the calling Form invisible until all of the Reports opened by it have been closed, when it...
0
isladogs
by: isladogs | last post by:
The next online meeting of the Access Europe User Group will be on Wednesday 6 Dec 2023 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, Mike...
4
by: GKJR | last post by:
Does anyone have a recommendation to build a standalone application to replace an Access database? I have my bookkeeping software I developed in Access that I would like to make available to other...
3
SueHopson
by: SueHopson | last post by:
Hi All, I'm trying to create a single code (run off a button that calls the Private Sub) for our parts list report that will allow the user to filter by either/both PartVendor and PartType. On...

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.