martedì 20 agosto 2013

Ordinamento ascendente e decrescente su griglia in c#

Un pochino laborioso, ma con questo esempio si può creare un "sorting" su un qualsiasi campo di una GridView con c#.
Selezionando con il mouse la freccia "up" o "down" vicino al campo da ordinare, tutti i campi della griglia si ordinano automaticamente.
La griglia è il componente classico GridView utilizzato in una pagina aspx con Visual Studio 2010 framework 4.0 (ma si trova anche con il 3.5).
Di seguito il codice della pagina aspx e il codice da integrare nel file .cs
(Da non dimenticare di reperire le immagini delle frecce "up" e "down").

<%@ Page Title="Home page" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true"
CodeFile="Default.aspx.cs" Inherits="_Default" %>

<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false"
OnPageIndexChanging="GridView1_PageIndexChanging" OnSorting="GridView1_Sorting" 
OnRowCreated="GridView1_RowCreated"
AllowSorting="True" DataKeyNames="id" AllowPaging="True" PageSize="15" 
PageIndex="0" PagerSettings-Mode="NumericFirstLast"
PagerSettings-FirstPageText="Prima" PagerSettings-LastPageText="Ultima" 
EmptyDataText="No data available."
>
<Columns>
<asp:TemplateField HeaderText="id" ItemStyle-Width="50" SortExpression="id">
<ItemStyle HorizontalAlign="left"/>
<ItemTemplate>
<%# Eval("id")%>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="description" ItemStyle-Width="150" SortExpression="description">
<ItemStyle HorizontalAlign="left"/>
<ItemTemplate>
<%# Eval("description")%>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</asp:Content>


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
CaricaGridView("id", SortDirection.Ascending);
}

protected DataTable dataTable()
{
DataTable dt = new DataTable();
dt = new DataTable("dt");
dt.Columns.Add(new DataColumn("id", typeof(string)));
dt.Columns.Add(new DataColumn("description", typeof(string)));
DataRow dataRow = dt.NewRow();
dataRow = dt.NewRow();
dataRow["id"] = "1";
dataRow["description"] = "ALFAROMEO";
dt.Rows.Add(dataRow);
dataRow = dt.NewRow();
dataRow["id"] = "2";
dataRow["description"] = "FORD";
dt.Rows.Add(dataRow);
dataRow = dt.NewRow();
dataRow["id"] = "3";
dataRow["description"] = "VOLVO";
dt.Rows.Add(dataRow);

return dt;
}


protected void CaricaGridView(string sortString, SortDirection sortDirection)
{
DataView dataView = null;
try
{
dataView = new DataView(dataTable());
if (sortDirection.Equals(SortDirection.Ascending))
dataView.Sort = sortString + " " + "ASC";
else
dataView.Sort = sortString + " " + "DESC";

GridView1.DataSource = dataView;
GridView1.DataBind();
}
catch (Exception ex)
{

}
finally
{
if (dataView != null)
dataView.Dispose();
}
}

protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{

GridView1.PageIndex = e.NewPageIndex;

DataView dataView = null;
try
{
dataView = new DataView(dataTable());
String SortExpDirection = Convert.ToString(ViewState["SortExpression"]);
if (SortExpDirection == "")
SortExpDirection = "Id";
if (Convert.ToString(ViewState["SortDirection"]).Equals(""))
ViewState["SortDirection"] = "DESC";
SortExpDirection += " " + ViewState["SortDirection"];
dataView.Sort = SortExpDirection;
GridView1.DataSource = dataView;
GridView1.DataBind();
}
catch (Exception ex)
{

}
finally
{
if (dataView != null)
dataView.Dispose();
}
}

protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
{
if (ViewState["SortExpression"] != null)
{
String sortDirection = Convert.ToString(ViewState["SortDirection"]);
String sortExpression = Convert.ToString(ViewState["SortExpression"]);
if (sortExpression == e.SortExpression)
{
ViewState["SortDirection"] = ChangeDirection(sortDirection);
}
else
{
ViewState["SortExpression"] = e.SortExpression;
ViewState["SortDirection"] = "ASC";
}
}
else
{
ViewState["SortExpression"] = e.SortExpression;
ViewState["SortDirection"] = "ASC";
}
DataView dataView = null;
try
{
dataView = new DataView(dataTable());
String SortExpDirection = Convert.ToString(ViewState["SortExpression"]);
SortExpDirection += " " + ViewState["SortDirection"];
dataView.Sort = SortExpDirection;
GridView1.DataSource = dataView;
GridView1.DataBind();
}
catch (Exception ex)
{

}
finally
{
if (dataView != null)
dataView.Dispose();
}
}

protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
{
try
{
if (e.Row.RowType == DataControlRowType.Header)
{
string NomeColonna;
for (int i = 0; i < 4; i++)
{
// Recupero il controllo che sta nella cella dell'header
//che è un LinkButton
LinkButton LinkButtonOrdinamento = (LinkButton)e.Row.Cells[i].Controls[0];
NomeColonna = LinkButtonOrdinamento.Text;

//Creo il controllo ImageButton
ImageButton ImageButtonOrdinamento = new ImageButton();
ImageButtonOrdinamento.CommandName = LinkButtonOrdinamento.CommandName;
string commandArgument = LinkButtonOrdinamento.CommandArgument;
ImageButtonOrdinamento.CommandArgument = commandArgument;
ImageButtonOrdinamento.ToolTip = "Ordina per " + NomeColonna;
ImageButtonOrdinamento.Width = (Unit)10;

//stabilisco l'immagine da visualizzare
ImageButtonOrdinamento.ImageUrl = "~/images/sort_up_blank.png";
if (ViewState["SortExpression"] != null)
{
String sortExpression = Convert.ToString(ViewState["SortExpression"]);
if (LinkButtonOrdinamento.CommandArgument == sortExpression)
{
if (Convert.ToString(ViewState["SortDirection"]) == "DESC")
{
ImageButtonOrdinamento.ImageUrl = "~/images/sort_down.png";
}
else
{
ImageButtonOrdinamento.ImageUrl = "~/images/sort_up.png";
}
}
}
ImageButtonOrdinamento.Width = Unit.Pixel(16);
ImageButtonOrdinamento.Height = Unit.Pixel(16);
//Creo il controllo Label
Label labelNomeColonna = new Label();
labelNomeColonna.Text = NomeColonna + " ";
Table tableOrd = new Table();

TableRow tableRowOrd = new TableRow();
TableCell tableCell0 = new TableCell();
tableCell0.Controls.Add(labelNomeColonna);
tableRowOrd.Cells.Add(tableCell0);
TableCell tableCell1 = new TableCell();
tableCell1.Controls.Add(ImageButtonOrdinamento);
tableRowOrd.Cells.Add(tableCell1);
tableOrd.Rows.Add(tableRowOrd);

//cancello il controllo linkbutton dalla cella
e.Row.Cells[i].Controls.Remove(LinkButtonOrdinamento);

//Aggiungo il nuovo controllo
e.Row.Cells[i].Controls.Add(tableOrd);

}
}
}
catch (Exception ex)
{

}
}
public static String ChangeDirection(String oldDirection)
{
String newDirection = "";
switch (oldDirection)
{
case "ASC":
newDirection = "DESC";
break;
default:
newDirection = "ASC";
break;
}
return newDirection;
}
}

Ordinamento

Nessun commento:

Posta un commento