473,729 Members | 2,177 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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.Collecti ons;
using System.Componen tModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.Sess ionState;
using System.Web.UI;
using System.Web.UI.W ebControls;
using System.Web.UI.H tmlControls;

namespace WebApplication2
{
/// <summary>
/// Summary description for WebForm1.
/// </summary>
public class WebForm1 : System.Web.UI.P age
{
protected System.Web.UI.W ebControls.Data Grid ItemsGrid;

private void Page_Load(objec t sender, System.EventArg s e)
{
ItemsGrid.DataS ource = CreateDataSourc e();
ItemsGrid.DataB ind();

}
ICollection CreateDataSourc e()
{

// 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("Int egerValue", typeof(Int32))) ;
dt.Columns.Add( new DataColumn("Str ingValue", typeof(String)) );
dt.Columns.Add( new DataColumn("Cur rencyValue", 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(EventArg s e)
{
//
// CODEGEN: This call is required by the ASP.NET Web Form Designer.
//
InitializeCompo nent();
base.OnInit(e);
}

/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeCompo nent()
{
this.ItemsGrid. PageIndexChange d += new System.Web.UI.W ebControls.Data GridPageChanged EventHandler(th is.ItemsGrid_Pa geIndexChanged) ;
this.ItemsGrid. SortCommand += new System.Web.UI.W ebControls.Data GridSortCommand EventHandler(th is.ItemsGrid_So rtCommand);
this.Load += new System.EventHan dler(this.Page_ Load);

}
#endregion

private void ItemsGrid_SortC ommand(object source, System.Web.UI.W ebControls.Data GridSortCommand EventArgs e)
{

// Retrieve the data source from session state.
DataTable dt = (DataTable)Sess ion["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.SortExpressio n + " ASC";
Session["sort"] = "DESC";
}
else
{
dv.Sort = e.SortExpressio n + " 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.DataS ource = dv;
ItemsGrid.DataB ind();

}

private void ItemsGrid_PageI ndexChanged(obj ect source, System.Web.UI.W ebControls.Data GridPageChanged EventArgs e)
{
// For the DataGrid control to navigate to the correct page when
// paging is allowed, the CurrentPageInde x property must be updated
// programmaticall y. This process is usually accomplished in the
// event-handling method for the PageIndexChange d event.

// Set CurrentPageInde x to the page the user clicked.
ItemsGrid.Curre ntPageIndex = e.NewPageIndex;

// Rebind the data to refresh the DataGrid control.
ItemsGrid.DataS ource = CreateDataSourc e();
ItemsGrid.DataB ind();

}

}
}



<%@ Page language="c#" Codebehind="Web Form1.aspx.cs" AutoEventWireup ="false" Inherits="WebAp plication2.WebF orm1" %>
<!doctype html public "-//w3c//dtd html 4.0 transitional//en" >
<html>
<head>
<title>WebForm1 </title>
<meta name="GENERATOR " content="Micros oft Visual Studio .NET 7.1">
<meta name="CODE_LANG UAGE" content="C#">
<meta name="vs_defaul tClientScript" content="JavaSc ript">
<meta name="vs_target Schema" content="http://schemas.microso ft.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="T rue" allowpaging="Tr ue" pagesize="2"></asp:datagrid>
</form>
</body>
</html>
Nov 18 '05 #1
1 2350
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****@discuss ions.microsoft. com> wrote in message
news:B7******** *************** ***********@mic rosoft.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.Collecti ons;
using System.Componen tModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.Sess ionState;
using System.Web.UI;
using System.Web.UI.W ebControls;
using System.Web.UI.H tmlControls;

namespace WebApplication2
{
/// <summary>
/// Summary description for WebForm1.
/// </summary>
public class WebForm1 : System.Web.UI.P age
{
protected System.Web.UI.W ebControls.Data Grid ItemsGrid;

private void Page_Load(objec t sender, System.EventArg s e)
{
ItemsGrid.DataS ource = CreateDataSourc e();
ItemsGrid.DataB ind();

}
ICollection CreateDataSourc e()
{

// 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("Int egerValue", typeof(Int32))) ; dt.Columns.Add( new DataColumn("Str ingValue", typeof(String)) ); dt.Columns.Add( new DataColumn("Cur rencyValue", 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(EventArg s e)
{
//
// CODEGEN: This call is required by the ASP.NET Web Form Designer. //
InitializeCompo nent();
base.OnInit(e);
}

/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeCompo nent()
{
this.ItemsGrid. PageIndexChange d += new System.Web.UI.W ebControls.Data GridPageChanged EventHandler(th is.ItemsGrid_Pa g
eIndexChanged); this.ItemsGrid. SortCommand += new System.Web.UI.W ebControls.Data GridSortCommand EventHandler(th is.ItemsGrid_So r
tCommand); this.Load += new System.EventHan dler(this.Page_ Load);

}
#endregion

private void ItemsGrid_SortC ommand(object source, System.Web.UI.W ebControls.Data GridSortCommand EventArgs e) {

// Retrieve the data source from session state.
DataTable dt = (DataTable)Sess ion["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.SortExpressio n + " ASC";
Session["sort"] = "DESC";
}
else
{
dv.Sort = e.SortExpressio n + " 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.DataS ource = dv;
ItemsGrid.DataB ind();

}

private void ItemsGrid_PageI ndexChanged(obj ect source, System.Web.UI.W ebControls.Data GridPageChanged EventArgs e) {
// For the DataGrid control to navigate to the correct page when // paging is allowed, the CurrentPageInde x property must be updated // programmaticall y. This process is usually accomplished in the // event-handling method for the PageIndexChange d event.

// Set CurrentPageInde x to the page the user clicked.
ItemsGrid.Curre ntPageIndex = e.NewPageIndex;

// Rebind the data to refresh the DataGrid control.
ItemsGrid.DataS ource = CreateDataSourc e();
ItemsGrid.DataB ind();

}

}
}



<%@ Page language="c#" Codebehind="Web Form1.aspx.cs" AutoEventWireup ="false" Inherits="WebAp plication2.WebF orm1" %> <!doctype html public "-//w3c//dtd html 4.0 transitional//en" >
<html>
<head>
<title>WebForm1 </title>
<meta name="GENERATOR " content="Micros oft Visual Studio .NET 7.1">
<meta name="CODE_LANG UAGE" content="C#">
<meta name="vs_defaul tClientScript" content="JavaSc ript">
<meta name="vs_target Schema" content="http://schemas.microso ft.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="T rue" allowpaging="Tr ue" 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
1641
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 reading round the newsgroups, it seems that a custom 'IComparer' is the answer, but I'm not quite sure how to do this. Really, how to get at the IComparer that the DataGrid/DataView uses for sorting. Can anyone point me towards a nice example...
2
945
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 datagrid. HTML Datagrid1 TemplateColumn Table Header information Detail Information
1
2059
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 to scroll the table up and down or from right to the left the content of the active cell will be selected as if for copy/paste. How can I deactivate such a behaviour?
3
3127
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 sorts twice because I inserted a messagebox in the dgMouse (MouseUp) event. Before ok is pressed, the table changes from the order it was loaded to ascending order. After ok is pressed, it goes to descending. The code is below. Any idea why...
7
2465
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 Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load 'Put user code to initialize the page here
4
2112
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 codebehind file. I am using c#. Thanks Manny
5
2529
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 I cannot sort the data when I click on the column header. I have set the tablestype.allowsorting = true, but this has no effect.
1
7134
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 the first column in the grid only. I havent found a way to reliably do this yet. I tried putting the following code in the datagrid's mouse down event Dim hti As DataGrid.HitTestInfo
0
2088
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 help........pls urgent ========================================================= <%@ Page Language="vb" AutoEventWireup="false" Codebehind="WebForm3.aspx.vb" Inherits="TestDatagrids.WebForm3"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">...
0
8913
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9426
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9280
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
9142
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8144
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6016
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4525
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4795
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
2162
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.