Filtrare DataGrid
di
John Kilgo
Data di pubblicazione: 20/11/2003
Voto della community: n.g.
(Votanti: 0)
In questo articolo vediamo come filtrare un DataGrid rispetto a due colonne. Ueremo la tabella Products del database Northwind; accederemo inoltre alla tabella Categories per popolare uno dei due DropDownList di cui ci serviremo. Faremo in modo che selezionando una categoria dal DropDownList il contenuto del DataGrid venga aggiornato per visualizzare solo i prodotti di quella categoria. La tabella Products contiene anche i prezzi di ciascun prodotto; saremo in grado di scegliere anche gli intervalli di prezzo in base a cui filtrare il DataGrid. Per fare ciò ci serviremo di un DataView. Per prima cosa diamo un'occhiata alla pagina .aspx DGFilter.aspx. Questa definisce i due DropDownList e il nostro Datagrid. Le uniche cose cui porre attenzione sono i due DropDownList. Notare che abbiamo settato l'AutoPostBack a 'true' così che il DataGrid sarà filtrato selezionando un elemento dei due DropDownList. Notiamo inoltre che abbiamo settato una procedura di event handling agganciata all'evento OnSelectedIndexChanged. Tale procedura è la ChangeFilter del nostro file code-behind. <%@ Page Language="vb" AutoEventWireup="false" Src="DGFilter.aspx.vb" Inherits="DGFilter"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <html> <head> <title>DGFilter</title> <meta name="GENERATOR" content="Microsoft Visual Studio.NET 7.0"> <meta name="CODE_LANGUAGE" content="Visual Basic 7.0"> <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:Label ID="lblCategory" Text="Category: " Runat="server" /> <asp:DropDownList ID="ddlCategoryFilter" AutoPostBack="True" OnSelectedIndexChanged="ChangeFilter" Runat="server" /> <asp:Label ID="lblPriceFilter" Text="Price: " Runat="server" /> <asp:DropDownList ID="ddlPriceFilter" AutoPostBack="True" OnSelectedIndexChanged="ChangeFilter" Runat="server"> <asp:ListItem Value="0" Selected="True">All Prices</asp:ListItem> <asp:ListItem Value="1"><= $20</asp:ListItem> <asp:ListItem Value="2">$20.01 - $40.00</asp:ListItem> <asp:ListItem Value="3">$40.01 - $60.00</asp:ListItem> <asp:ListItem Value="4">$60.01 - $80.00</asp:ListItem> <asp:ListItem Value="5">Over $80.00</asp:ListItem> </asp:DropDownList> <p></p> <asp:DataGrid ID="dtgProducts" Runat="server" HeaderStyle-BackColor="IndianRed" HeaderStyle-ForeColor="White" HeaderStyle-Font-Name="Verdana" HeaderStyle-Font-Size="10" ItemStyle-BackColor="Gainsboro" ItemStyle-Font-Name="Verdana" ItemStyle-Font-Size="10" CellPadding="4" GridLines="Both" /> </form> </body> </html> Guardiamo ora, per il code-behind, DGFilter.aspx.vb. Sarà spezzato in due parti per una migliore comprensione delle sue sezioni. Nella prima parte (a seguire) notiamo che l'aver settato il filtro della categoria ad 1 (Beverages) e il filtro prezzo a UnitPrice>0 comporta la visualizzazione di tutti i prezzi. Nell'evento Page_Load chiamiamo FillCategoryDropDown (la procedura successiva) che riempie il DropDownList delle categorie con le varie categorie di prodotti. Più sotto troviamo BindTheData, che si connette al database, riempie un DataSet con i dati della tabella Products quindi crea un DataView strCategoryFilter e strPriceFilter come RowFilter. Questa operazione è analoga all'aggiunta di una clausola WHERE del tipo "WHERE CategoryID=1 AND UnitPrice>0" per la prima 'scrematura' dei dati. Come vediamo nella seconda parte del codice, strCateogryFilter o strPricefilter possono cambiare in base alle selezioni compiute dall'utente nei DropwDownList. Imports System.Data Imports System.Data.SqlClient Imports System.Configuration Public Class DGFilter Inherits System.Web.UI.Page Public strCategoryFilter As String = "CategoryID=1" Public strPriceFilter As String = "UnitPrice>0" Public strSql As String Protected ddlCategoryFilter As System.Web.UI.WebControls.DropDownList Protected ddlPriceFilter As System.Web.UI.WebControls.DropDownList Protected WithEvents lblCategory As System.Web.UI.WebControls.Label Protected WithEvents lblPriceFilter As System.Web.UI.WebControls.Label Protected dtgProducts As System.Web.UI.WebControls.DataGrid Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load If Not IsPostBack Then FillCategoryDropDown() BindTheData() End If End Sub Sub FillCategoryDropDown() Dim objConn As SqlConnection objConn = New SqlConnection("server=(local);uid=sa;pwd=.....;database=Northwind") strSql = "Select CategoryName, CategoryID From Categories" Dim objCmd As New SqlCommand(strSql, objConn) Dim dataReader As SqlDataReader = Nothing Try objConn.Open() dataReader = objCmd.ExecuteReader() ddlCategoryFilter.DataSource = dataReader ddlCategoryFilter.DataTextField = "CategoryName" ddlCategoryFilter.DataValueField = "CategoryID" ddlCategoryFilter.DataBind() Catch exc As System.Exception Response.Write(exc.ToString()) Finally objConn.Dispose() End Try End Sub Sub BindTheData() Dim objConn As SqlConnection objConn = New SqlConnection("server=(local);uid=sa;pwd=....;database=Northwind") strSql = "Select ProductID, ProductName, CategoryID, UnitPrice From Products" Try Dim dataAdapter As New SqlDataAdapter(strSql, objConn) Dim dataSet As New DataSet() dataAdapter.Fill(dataSet, "Products") Dim dvProducts As New DataView(dataSet.Tables("Products")) dvProducts.RowFilter = strCategoryFilter & " AND " & strPriceFilter dtgProducts.DataSource = dvProducts dtgProducts.DataBind Catch exc As System.Exception Response.Write(exc.ToString()) Finally objConn.Dispose() End Try End Sub La parte due del codice, mostrata di seguito, contiene la parte più interessante relativamente all'oggetto dell'articolo. Ricordiamo che nel file .aspx settiamo un event handler chiamato ChangeFilter per entrambi i DropDownList. Questo è chiamato ogni volta che viene fatta una selezione nei DropDownList. Nel code-behind, ChangeFilter chiama due altre routine, FilterByCategory e FilterByPrice, prima di rieseguire il DataBinding. Alle due routine sono passati rispettivamente il SelectedItem.Value e il SelectedItem.Text dagli appropriati DropDownList. FilterByCategory semplicemente costruisce la stringa strCategory aggiungendo il CategoryID dal valore scelto dall'utente nel dropdown delle categorie. FilterByPrice riceve il Text dal corrispondente DropdownList e setta in maniera appropriata la "clausola WHERE" (strPriceFilter).
Sub ChangeFilter(Source As System.Object, e As System.EventArgs)
FilterByCategory(ddlCategoryFilter.SelectedItem.Value.ToString()) FilterByPrice(ddlPriceFilter.SelectedItem.Text.ToString()) BindTheData() End Sub Sub FilterByCategory(strCategory As String) strCategoryFilter = "CategoryID=" & strCategory End Sub Sub FilterByPrice(strPriceRange As String) Select Case strPriceRange Case "All Prices" strPriceFilter = "UnitPrice>0" Case "<= $20" strPriceFilter = "UnitPrice<=20" Case "$20.01 - $40.00" strPriceFilter = "UnitPrice>20 AND UnitPrice<=40" Case "$40.01 - $60.00" strPriceFilter = "UnitPrice>40 AND UnitPrice<=60" Case "$60.01 - $80.00" strPriceFilter = "UnitPrice>60 AND UnitPrice<=80" Case "Over $80.00" strPriceFilter = "UnitPrice>80" End Select End Sub End Class Spero abbiate trovato il codice abbastanza coinciso da essere seguito senza difficltà. Essenzialmente, stiamo passando il valore del DropDownList delle categorie e il Text del DropDownList a delle routine che costruiscono stringhe contenenti i nostri filtri (strCategoryFilter e strPriceFilter) i quali sono restituiti alla procedura BindTheData per essere incorporati nel filtro del DataView. Si ringrazia DotNetJohn.com per la gentile concessione dell'articolo (Filtering DataGrid).
|
||||||||||||||||||||||||