<< Click to Display Table of Contents >> GridView - ordenar via JS (jquery table sorter) |
![]() ![]() ![]() |
Objetivo
Ao clicar no cabeçalho ordenar por qualquer coluna (múltiplas colunas é permitido)
O que precisa?
tablesorter.min.js
tablesort.min.css
Baixe aqui:
Projeto
Default.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="Help.Default" %>
<html lang="pt-br">
<head runat="server">
<meta charset="UTF-8" />
<title>TableSorter</title>
<link rel="stylesheet" href="css/bootstrap.min.css" />
<link rel="stylesheet" href="css/bootstrap-theme.min.css" />
<link href="css/tablesort.min.css" rel="stylesheet" />
<style>
.img {
margin-top: 40px;
margin-bottom: 40px;
}
.container {
margin-top: 20px;
}
.table tbody tr:hover td {
background-color: lightyellow;
}
</style>
</head>
<body>
<div class="container">
<form id="form1" runat="server">
<asp:GridView ID="Grid" runat="server" CssClass="table table-striped table-bordered table-condensed" AutoGenerateColumns="False" ItemType="System.Data.DataRowView">
<Columns>
<asp:BoundField DataField="Codigo" HeaderText="Código" />
<asp:TemplateField HeaderText="Nome">
<ItemTemplate>
<asp:HyperLink ID="lnkEditar" runat="server"><%#:Item["Nome"]%></asp:HyperLink>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Salário">
<ItemTemplate>
<div class="direita">
<asp:HyperLink ID="lnkEditar" runat="server"><%#:Decimal.Parse(Item["Salario"].ToString()).ToString("#,##0.00")%></asp:HyperLink>
</div>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Data">
<ItemTemplate>
<div class="centro">
<asp:HyperLink ID="lnkEditar" runat="server"><%#:DateTime.Parse(Item.Row["Nasc"].ToString()).ToString("dd-MMM-yy ddd")%></asp:HyperLink>
</div>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</form>
</div>
<script src="js/jquery-2.2.0.min.js"></script>
<script src="js/tablesorter.min.js"></script>
<script src="js/funcoes-tablesorter.min.js"></script>
<script>
$(document).ready(function () {
$("#<%=Grid.ClientID%>").tablesorter({
sortList: [[1, 1]],
headers: {
2: { sorter: "valor" },
3: { sorter: "data" }
}
});
}
);
/*
If you are using an UpdatePanel, you need to consider using the PageLoad function (JavaScript):
$("#grid").tablesorter();
*/
</script>
</body>
</html>
Default.cs
using System;
using System.Web.UI.WebControls;
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Pessoas p = new Pessoas();
Grid.DataSource = p.Listar();
Grid.DataBind();
Grid.UseAccessibleHeader = true;
Grid.HeaderRow.TableSection = TableRowSection.TableHeader; // isso coloca o thead dentro da tag table
Grid.FooterRow.TableSection = TableRowSection.TableFooter; // isso coloca o tfooter dentro da tag table
}
/*
// se a Grid estiver dentro de um update panel você de fazer desse jeito:
protected void Grid.DataBound(object sender, EventArgs e)
{
if (this.gvEmployees.Rows.Count > 0)
{
Grid.UseAccessibleHeader = true;
Grid.HeaderRow.TableSection = TableRowSection.TableHeader;
Grid.FooterRow.TableSection = TableRowSection.TableFooter;
}
}
*/
}
}
funcoes-tablesorter.js
function trocaMesTextoPorNumero(data) {
var meses = ["jan", "fev", "mar", "abr", "mai", "jun", "jul", "ago", "set", "out", "nov", "dez"];
for (i = 0; i < meses.length; i++) {
// encontrou este mes na data?
if (data.indexOf(meses[i]) > -1) {
// troca texto por numero
var numero = (i + 1).toString();
if (numero.length < 2)
numero = "0" + numero;
data = data.replace(meses[i], numero);
break;
};
}
return data;
}
// define um parser chamado VALOR
$.tablesorter.addParser(
{
// set a unique id
id: 'valor',
is: function (s) { // return false so this parser is not auto detected
return false;
},
format: function (valor) {
valor = valor.trim();
if (valor === "") { // vazio é zero
valor = 0;
} else {
valor = valor.replace(".", "").replace(",", "."); // tira os . e troca as , por .
valor = parseFloat(valor);
}
return valor;
},
// set type, either numeric or text
type: 'numeric'
});
// parser para configurar a data para o formato do Brasil
$.tablesorter.addParser({
id: 'data',
is: function (s) { // return false so this parser is not auto detected
return false;
},
format: function (s, table) {
s = s.trim();
// se a data é formata algo como "01-jan-16 seg" > remove o " seg"
if (s.indexOf(" ") > -1) {
s = s.split(" ")[0];
}
s = trocaMesTextoPorNumero(s);
var matriz = s.split("-"); // separa por '-'
// dai verifica se é menor que 40 (se for é prefixo 20 - 2040) se for maior que 40 é prefixo 19.
if (matriz[2].length == 2) {
if (matriz[2] < "40")
matriz[2] = "20" + matriz[2];
else
matriz[2] = "19" + matriz[2];
}
var data = new Date(matriz[2], matriz[1] - 1, matriz[0]); // formata ano-mes-dia (USA)
return $.tablesorter.formatFloat(data.getTime()); // transforma em datetime para ordenar
},
type: 'numeric'
});
tablesort.css
Para facilitar os ícones de ascendente e descendente no cabeçalho
.headerSortUp {
background-repeat: no-repeat;
background-position: right center;
background-repeat: no-repeat;
background-image: url(asc.gif);
background-color: lightcyan;
}
.headerSortDown {
background-position: top;
background-position: right center;
background-repeat: no-repeat;
background-image: url(desc.gif);
background-color: lightyellow;
}
Pessoas.cs
using System;
using System.Data;
namespace Help
{
public class Pessoas
{
private DataTable Dados;
private void Nova(int aId, string aNome, decimal aSalario, DateTime aNasc)
{
DataRow dr = Dados.NewRow();
dr["Codigo"] = aId;
dr["Nome"] = aNome;
dr["Salario"] = aSalario;
dr["Nasc"] = aNasc;
Dados.Rows.Add(dr);
}
public Pessoas()
{
Dados = new DataTable();
Dados.Columns.Add(new DataColumn("Codigo", typeof(System.Int32)));
Dados.Columns.Add(new DataColumn("Nome", typeof(System.String)));
Dados.Columns.Add(new DataColumn("Salario", typeof(System.Decimal)));
Dados.Columns.Add(new DataColumn("Nasc", typeof(System.DateTime)));
Nova(1, "Junior", (decimal)1000.50, new DateTime(1977, 1, 1));
Nova(2, "Flavio", (decimal)10.00, new DateTime(1978, 2, 10));
Nova(3, "Mario", (decimal)1.99, new DateTime(1985, 3, 21));
Nova(4, "Luidi", (decimal)2.10, new DateTime(1986, 4, 30));
Nova(5, "Peach", (decimal)34.12, new DateTime(1990, 5, 2));
Nova(6, "Toad", (decimal)1101.22, new DateTime(2000, 6, 12));
Nova(7, "Rosalina", (decimal)10.14, new DateTime(2010, 7, 21));
Nova(8, "Ana", (decimal)45.89, new DateTime(2011, 8, 29));
Nova(9, "Kaylee", (decimal)22.88, new DateTime(2005, 9, 2));
Nova(10, "Mal", (decimal)10.50, new DateTime(2006, 10, 3));
Nova(11, "Jayne", (decimal)50.67, new DateTime(2000, 11, 14));
Nova(12, "Ana", (decimal)45.44, new DateTime(2010, 12, 22));
Nova(13, "Ana", (decimal)23.00, new DateTime(2002, 1, 24));
Nova(14, "Zoe", (decimal)1.10, new DateTime(1950, 2, 25));
Nova(15, "Simon", (decimal)12.01, new DateTime(1980, 3, 30));
Nova(16, "Book", (decimal)1123.02, new DateTime(1990, 4, 11));
Nova(17, "Universe", (decimal)543.22, new DateTime(1960, 5, 10));
Nova(18, "Zambo", (decimal)23.04, new DateTime(1956, 6, 9));
Nova(19, "Ana", (decimal)100.05, new DateTime(1999, 7, 8));
}
public DataTable Listar()
{
return Dados;
}
}
}