El hecho de lograr ambas tareas de forma simultanea en páginas ASP.NET presenta un pequeño cuidado; se debe mantener el índice de la página en la que estamos cuando establecemos un nuevo criterio de ordenamiento. De la misma forma debemos mantener el criterio de ordenamiento al cambiar el índice de la página a la que queremos acceder.
El código que sigue es un ejemplo o una de las formas, siempre hay mas de una forma :), de como se puede lograr esta tarea.-
- SortingPaging.aspx (nuestra página aspx)
<asp:GridView ID="gridSample" runat="server" AutoGenerateColumns="false"- SortingPaging.aspx.cs (nuestro archivo de code behind)
AllowPaging = "true" OnPageIndexChanging = "gridView_PageIndexChanging"
PageSize = "5"
AllowSorting = "true" OnSorting = "gridView_Sorting">
<Columns>
<asp:BoundField HeaderText="Nombre"
DataField="Nombre"
SortExpression = "Nombre" />
<asp:BoundField HeaderText="Edad"
DataField="edad"
SortExpression = "edad" />
</Columns>
</asp:GridView>
using System;
using System.Data;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class SortingPaging : Page {
protected void Page_Load(object sender, EventArgs e) {
DataSet ds = new DataSet();
// Aqui llenamos nuestro DataSet
DataView dv = ds.Tables[0].DefaultView;
dv = sortDataView(dv, true);
gridSample.DataSource = dv;
gridSample.DataBind();
}
private string GridSampleSortDirection {
get { return ViewState["SortDirection"] as string ?? "ASC"; }
set { ViewState["SortDirection"] = value; }
}
private string GridSampleSortExpression {
get { return ViewState["SortExpression"] as string ?? "Nombre"; }
set { ViewState["SortExpression"] = value; }
}
private string getSortDirection() {
switch (GridSampleSortDirection) {
case "ASC":
GridSampleSortDirection = "DESC";
break;
case "DESC":
GridSampleSortDirection = "ASC";
break;
}
return GridSampleSortDirection;
}
protected void gridView_PageIndexChanging(object sender, GridViewPageEventArgs e) {
gridSample.DataSource = sortDataView(gridSample.DataSource as DataView, true);
gridSample.PageIndex = e.NewPageIndex;
gridSample.DataBind();
}
protected DataView sortDataView(DataView dataView, bool isPageIndexChanging) {
if (isPageIndexChanging) {
dataView.Sort = string.Format("{0} {1}",
GridSampleSortExpression,
GridSampleSortDirection);
} else {
dataView.Sort = string.Format("{0} {1}",
GridSampleSortExpression,
getSortDirection());
}
return dataView;
}
protected void gridView_Sorting(object sender, GridViewSortEventArgs e) {
GridSampleSortExpression = e.SortExpression;
int pageIndex = gridSample.PageIndex;
gridSample.DataSource = sortDataView(gridSample.DataSource as DataView, false);
gridSample.DataBind();
gridSample.PageIndex = pageIndex;
}
}
40 comentarios:
hola.. con ese codigo me aparece un error en el Load, en esta linea
DataView dv = ds.Tables[0].DefaultView
Dice que no puede encontrar la Tabla 0...
le faltará algo?
Si lo copias tal cual, de seguro te dará error. Tienes que implementar el llenado del DataSet tal cual lo expresa el comentario
Mi pregunta es, como ordeno la columna Fecha, hasta ahora lo hace perfecto con otras columnas pero no ordena correctamente las fechas ya que lo hace alfabéticamente, habrá algunas solución fácil a eso?
Desde ya muchas gracias.
Hola Pablo tengo una duda, intendo crear dinamicamente un gridview el cual lo lleno con ciertos datos y intento activar la paginacion y no lo permite. Todo esto es puro codigo de c# con asp net.
Disculpa pero no entiendo la pregunta, podrias darme mas detalles de como intentas activar la paginación?
Hola lo que pasa es que el grid lo creo con codigo de c#.
gridview ogrd = new gridview();
ogrd.allowpaging = true ;
gd.BottomPagerRow.Visible = true;
....etc
pero cuando pongo en ciclo for que carga 10 datos no hace el paginado en la propiedad de pagesize le pongo 5 pero nada
tienes algun mail para contactarte y pasarte mi proy. gracias
I agree with you.bad credit loans for unemployed
Thanxx
Nice to see you back. And again by having an interesting post.
thanxx
newegg promo code
Muy buen articulo, estoy casi 100% de acuerdo contigo :)
Magnificent beat ! I woulԁ like to apρrеntiсе аt
the same time as you amenԁ уour sitе, hoω can і subѕсribe for а web-site
web site? Τhe аccount helρed me a aρрlicable deal.
I werе tiny bit acquаinted of thiѕ yοuг broadcast offereԁ bright
сlear idеa
Feel free to ѕurf to mу web-site fast long term loans
Hi thегe ωould уοu mіnd stating whiсh blog platfoгm yοu're working with? I'm gоіng to stаrt my own blοg in thе near future but I'm having a tough time selecting between BlogEngine/Wordpress/B2evolution and Drupal. The reason I ask is because your design and style seems different then most blogs and I'm looking for sοmething unique.
P.S My apologiеѕ for getting off-tορic but I had
to aѕk!
my web sіtе loans and fast
I feel like I've been on the receiving end of a stampeed after reading all this. It's bloody challenging wakіng up
with а hangover.
My wеb page - best rate loan
Very еnеrgetic blog, I liκed thаt
a lot. Will there be а pаrt 2?
Feel free to suгf to my ωeb-site; best personal loan
This has сaused me to wondeг if thегe's a couple of ways I could do things a little better.
Also visit my web site - best bank loans
I Οncе upon a time І uѕed to study editorials іn newspaрers but now aѕ I am a uѕer οf net therefore from now I am uѕing net for content,
thanks to web.
Ϻy website - Best Unsecured Loans
Hellο, I used to always check web ρostѕ
hеre every weeκ, ѕince i еnjoy to finԁ
οut more and more.
Аlѕo ѵiѕit my sitе ... best loans for bad credit
I am ωondеring at ωhat age уou begin
to get ωіsеr and get used to аll this nonsense.
my page :: www.cash1Loans.Com
It's not my aim to be a pest, I think you can do better stuff than this. More content would be a start.
Also visit my blog: http://associazionismo.altervista.org/
I might get around to dоing somеthing similar myself soon, if I can find fіnance.
Also visit mу wеbѕite :: loan broker
Will do - I'll add them tomorrow, when I've got some time.
my ρаge fast money loans
Havе not hеard about this mаttеr untіl now, I ought to do so.
Here is mу web blog ... best bank loans
Looks lіκe my tablet has dеcidеd to ωork ρroperly thiѕ week, I can аctually reply.
If I сan say, I wouldn't bother myself.
Here is my blog post ... loans broker
Havеn't yet read about this idea until now, I will do so soon.
Take a look at my weblog - best unsecured loans
Aw, tгу not to mind. It's the old adage...when it can't be
ԁοne, bеttеr ԁo it уourself.
Here іs my blog post ... best loans uk
Good intro, mаde me гead it all. Mine alwaуs
sеem to waffle on, youгs is rеally еffectual.
my blog poѕt :: best personal loans
Informative гeаԁ, esρеciаlly pоstеr numbeг four ӏ thіnk.
Hopefully I'll remember it.
My homepage; best personal loans
Dont belief I κnоw ωot u mean bout this 2 b purfectly honest.
Μyt av to go еlswherе 2 fоr
helр.
Hеre is my homepage http://Userforum.onleihe.de//index.php/index.php?page=User&userid=2219
Thаt's what I was saying.... You'd havе to bе ignorant
tо think anу ԁifferent.
Herе is my weblog unsecured personal loans
Looks liκe the сat's out of the bag on this... have a look to see whats coming up....
my page ... personal loans uk
I peгѕonаllу dіdn't spend too long on this, but I can tell it's obviouslу worth it.
Also visit my ωeb-sіte best loans on the market
That's what I was thinking.... You'ԁ hаve tο be silly to think
diffеrеnt.
Also νisit my weblog - best loans uk
I feel as though ӏ coulԁ learn аbout this for ageѕ, it's riveting. I don't even
need a cuppa yet.
Also visit mу blog post; get fast cash loans
Yоu touch оn thiѕ a lot moгe сlеarly than I ever could - pеrhaps why I don't have a thriving blog of my own.
My page best personal loan
Υοu touch on thіs а lot bettеr than I ever could - which іs probably why I don't have a thriving blog!
my website; unsecured loans
Now then, іts quеstіon time, do we get the chance to asκ a challenging question?
Also vіsit mу wеb blog ... best loans
Theге's nearly always a new problem waiting round the next corner. Never done eh!
Feel free to surf to my blog post; bad credit personal loans
Went tο сopy from windows Viѕta аnd then
attemptеd to ρaѕtе into android. Mаybe I need
to rеtire from lіfe.
Alѕo visit mу web pаgе .
.. best apr loans
Тhe ԁata is nіgh-on insignificant, meaning the outcome mаκes ѵery littlе senѕe.
Also visit my ωeb page ... best personal loans
I have only read a fеw artiсleѕ but І'm already captivated. Need to spend a whole afternoon going over the discussions on here.
My homepage; loans site
bbq timе / beer time is appгoaching.
If I can just comprehend thiѕ blogpost іn the
next few minutes I'll be able to unwind.
my blog ... personal loans bad credit
Publicar un comentario