News Ticker

Menu

Sử dụng Dropdownlist để lọc dữ liệu trong Gridview HeaderTemplate

(Lọc dữ liệu từ Dropdownlist trong Gridview) – Chức năng AutoFilter trong Excel giúp người sử dụng lọc và tìm dữ liệu dễ dàng và thuận tiện. Chỉ cần kích vào mũi tên tại mỗi cột dữ liệu, một danh sách lựa chọn xuất hiện và người dùng chỉ cần chọn thì toàn bộ dữ liệu sẽ được lọc theo tiêu chí đã chọn.

Xem những Video hay dành cho thiếu nhi - Nghe trên Youtube



Quay lại danh sách dữ liệu trong Gridview, người dùng sẽ rất khó để xem dữ liệu nếu không có các điều kiện để lọc. Bài viết dưới đây sẽ hướng dẫn các bạn cách xây dựng các điều kiện lọc trong chính các HeaderTemplate của Gridview.

Code Example C#, Code Example VB.NET
Code Example C#, Code Example VB.NET



B1: Download CSDL Northwind

B2Bổ xung thêm stored procedure trong SQL Server

USE [Northwind]
GO

CREATE PROCEDURE [dbo].[Pro_Products_List]
      @Keyword nvarchar(250),
      @SupplierID int,
      @CategoryID int
AS

declare @strSQL   nvarchar(1000)
declare @strWhere nvarchar(500)
declare @strOrder nvarchar (50)

set @strSQL= 'SELECT  Products.ProductID, Products.ProductName, Products.SupplierID, Suppliers.CompanyName, Products.CategoryID,
                      Categories.CategoryName, Products.QuantityPerUnit, Products.UnitPrice, Products.UnitsInStock,
                                Products.UnitsOnOrder, Products.ReorderLevel, Products.Discontinued
                    FROM    Products INNER JOIN
                      Suppliers ON Products.SupplierID = Suppliers.SupplierID INNER JOIN
                      Categories ON Products.CategoryID = Categories.CategoryID'

set @strWhere =' Where 1=1 '

if @Keyword<>''
      set @strWhere= @strWhere  +' And (ProductName like N''%' +@Keyword+'%'')'

if @SupplierID <>-1
    set  @strWhere= @strWhere + ' and (Products.SupplierID='+ convert(nvarchar,@SupplierID) + ')'

if @CategoryID <>-1
    set  @strWhere= @strWhere + ' and (Products.CategoryID='+ convert(nvarchar,@CategoryID) + ')'

set @strOrder =' Order by Products.ProductName'

set @strSQL=@strSQL+@strWhere+@strOrder
print @strSQL

exec sp_executesql @strSQL

B3: Tạo Project trong Microsoft Visual Studio 2010

Trong Visual Studio tạo 1 Class có tên: Utility và nhập đoạn Code phía dưới cho Class này.

Imports System.Data.SqlClient
Imports System.Data

Namespace FilterRecordsUsingDropDownListInHeaderTemplate

    Public Class SqlDataProvider

#Region "Membres Prives"

        Shared _IsError As Boolean = False
        Private _connectionString As String

#End Region

#Region "Constructeurs"

        Public Sub New()
            Try
                _connectionString = ConfigurationManager.ConnectionStrings("SiteSqlServer").ConnectionString
                _IsError = False
            Catch ex As Exception
                _IsError = True
            End Try
        End Sub

#End Region

#Region "Proprietes"

        Public ReadOnly Property ConnectionString() As String
            Get
                Return _connectionString
            End Get
        End Property

#End Region

#Region "Functions"

        Public Function FillTable(ByVal sql As String) As DataTable
            Try
                Dim tb As New DataTable
                Dim adap As New SqlDataAdapter(sql, _connectionString)
                adap.Fill(tb)
                Return tb
            Catch ex As Exception
                Return Nothing
            End Try
        End Function

        Public Function FillTable(ByVal ProcName As String, ByVal ParamArray Para() As ObjectPara) As DataTable
            Try
                Dim tb As New DataTable
                Dim adap As New SqlDataAdapter(ProcName, _connectionString)
                adap.SelectCommand.CommandType = CommandType.StoredProcedure
                If Not Para Is Nothing Then
                    For Each p As ObjectPara In Para
                        adap.SelectCommand.Parameters.Add(New SqlParameter(p.Name, p.Value))
                    Next
                End If
                adap.Fill(tb)
                Return tb
            Catch ex As Exception
                Return Nothing
            End Try
        End Function

#End Region

    End Class

    Public Class ObjectPara
        Dim _name As String
        Dim _Value As Object

        Sub New(ByVal Pname As String, ByVal PValue As Object)
            _name = Pname
            _Value = PValue
        End Sub

        Public Property Name() As String
            Get
                Return _name
            End Get
            Set(ByVal value As String)
                _name = value
            End Set
        End Property

        Public Property Value() As Object
            Get
                Return _Value
            End Get
            Set(ByVal value As Object)
                _Value = value
            End Set
        End Property

    End Class

End Namespace

Chú ý: Thuộc tính SiteSqlServer chính là chuỗi Connect với SQL Server trong file Web.Config

B4: Mở file Default.aspx dưới dạng HTML và  nhập mã HTML

<%@ Page Title="Filter Records using DropDownList in GridView HeaderTemplate in ASP.Net" Language="vb" MasterPageFile="~/Site.Master" AutoEventWireup="false" EnableEventValidation= "false" CodeBehind="Default.aspx.vb" Inherits="FilterRecordsUsingDropDownListInHeaderTemplate._Default" %>

<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
    <asp:ScriptManager ID="ScriptManager1" runat="server">
    </asp:ScriptManager>
    <h3>
        Filter Records using DropDownList in GridView HeaderTemplate in ASP.Net
    </h3>
    <asp:UpdatePanel ID="updatePanel" runat="server" UpdateMode="Conditional">
        <ContentTemplate>
            <table cellpadding="2" cellspacing="3" width="100%">
                <tr>
                    <td>
                        <h4>
                            <asp:Label ID="lblTotal" runat="server" Visible="false"></asp:Label>
                        </h4>
                    </td>
                    <td align="right">
                        <asp:TextBox ID="txtSearch" CssClass="form-control" ToolTip="Enter Keyword" runat="server" width="200px"></asp:TextBox>
                        <asp:ImageButton ID="cmdQuickSearch" runat="server" causesvalidation="false" imageurl="~/images/icon_search.gif"></asp:ImageButton>
                    </td>
                </tr>
                <tr>
                    <td colspan="2">
                        <asp:GridView ID="grvObject" runat="server" AllowPaging="true" PageSize="10" ShowHeaderWhenEmpty="true"
                            CssClass="GridStyle" BorderColor="#cbcbcb" BorderStyle="solid"
                            BorderWidth="1" AutoGenerateColumns="false" DataKeyNames="ProductID" width="100%">
                            <AlternatingRowStyle CssClass="GridStyle_AltRowStyle" />
                            <HeaderStyle CssClass="GridStyle_HeaderStyle" />
                            <RowStyle CssClass="GridStyle_RowStyle" />
                            <pagerstyle cssclass="GridStyle_pagination" />
                            <Columns>
                                <asp:BoundField ItemStyle-Width="16%" DataField="ProductName" HeaderText="ProductName" />
                                <asp:TemplateField HeaderText="Supplier">
                                    <ItemStyle  Width="12%"></ItemStyle>
                                    <HeaderTemplate>
                                        Supplier
                                        <asp:DropDownList ID="ddlSupplier" Width="180" CssClass="form-control" runat="server" AppendDataBoundItems="true" OnSelectedIndexChanged="SupplierChanged" AutoPostBack="true">
                                        </asp:DropDownList>
                                    </HeaderTemplate>
                                    <ItemTemplate>
                                        <asp:Label ID="lblSupplier" Text='<%# Eval("CompanyName") %>' runat="server" />
                                    </ItemTemplate>
                                </asp:TemplateField>
                                <asp:TemplateField HeaderText="Category">
                                    <ItemStyle  Width="12%"></ItemStyle>
                                    <HeaderTemplate>
                                        Category
                                        <asp:DropDownList ID="ddlCategory" CssClass="form-control" runat="server" AppendDataBoundItems="true" OnSelectedIndexChanged="CategoryChanged" AutoPostBack="true">
                                        </asp:DropDownList>
                                    </HeaderTemplate>
                                    <ItemTemplate>
                                        <asp:Label ID="lblCategory" Text='<%# Eval("CategoryName") %>' runat="server" />
                                    </ItemTemplate>
                                </asp:TemplateField>
                                <asp:TemplateField HeaderText="QuantityPerUnit">
                                    <ItemStyle  Width="8%"></ItemStyle>
                                    <ItemTemplate>
                                        <asp:Label ID="lblQuantityPerUnit" Text='<%# Eval("QuantityPerUnit") %>' runat="server" />
                                    </ItemTemplate>
                                </asp:TemplateField>
                                <asp:TemplateField HeaderText="UnitPrice">
                                          <ItemStyle HorizontalAlign="Right" width="8%" />   
                                    <ItemTemplate>
                                        <asp:Label ID="lblUnitPrice" Text='<%# Eval("UnitPrice") %>' runat="server"></asp:Label>
                                    </ItemTemplate>                          
                                </asp:TemplateField>                         
                            </Columns>                              
                        </asp:GridView>
                    </td>
                </tr>
                <tr id="trMessage" runat="server" visible="false">
                    <td colspan="2" align="center" valign="top">
                        <table style="BORDER-COLLAPSE: collapse" borderColor="#cccccc" cellspacing="1" cellpadding="2" width="100%" align="center" border="1">
                            <tr>
                                <td align="center" style="height:145px;padding-top:15px;">
                                    <asp:label id="lblMessage" runat="server" Text="No Data"></asp:label>
                                </td>
                            </tr>
                        </table>
                    </td>
                </tr>
            </table>
        </ContentTemplate>
    </asp:UpdatePanel>
</asp:Content>

B5: Viết Code cho file Default.aspx
C# Code
//Visit http://www.laptrinhdotnet.com for more ASP.NET Tutorials
using Microsoft.VisualBasic;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Diagnostics;

namespace FilterRecordsUsingDropDownListInHeaderTemplate
{
    public partial class _Default : System.Web.UI.Page
    {

        #region "ComboData"

        private void LoadDropDownList(DropDownList ucControl, string DataValueField, string DataTextField, string sql)
        {
            SqlDataProvider objSQL = new SqlDataProvider();
            DataTable objBind = objSQL.FillTable(sql);

            ucControl.Items.Clear();

            if (objBind != null)
            {
                ucControl.DataTextField = DataTextField;
                ucControl.DataValueField = DataValueField;
                ucControl.DataSource = objBind;
                ucControl.DataBind();
                ucControl.Items.Insert(0, (new ListItem("---All---", "-1")));
            }
        }

        #endregion

        #region "Bind Data"

        private void BindProducts()
        {
            DataTable objBind = new DataTable();
            int iTotal = 0;
            int SupplierID = -1;
            int CategoryID = -1;

            if (ViewState["Filter_Supplier"] != null)
            {
                SupplierID = Convert.ToInt32(ViewState["Filter_Supplier"]);
            }

            if (ViewState["Filter_Category"] != null)
            {
                CategoryID = Convert.ToInt32(ViewState["Filter_Category"]);
            }

            objBind = BindData(txtSearch.Text, SupplierID, CategoryID);

            if (objBind != null)
            {
                if (objBind.Rows.Count > 0)
                {
                    iTotal = objBind.Rows.Count;
                    grvObject.DataSource = objBind;
                    grvObject.DataBind();
                    trMessage.Visible = false;
                    lblTotal.Visible = true;
                    lblTotal.Text = "Total " + iTotal + " records";
                }
                else
                {
                    trMessage.Visible = true;
                    lblTotal.Visible = false;
                    grvObject.DataSource = new List<string>();
                    grvObject.DataBind();
                }
                updatePanel.Update();
            }
        }

        private DataTable BindData(string Keyword, int SupplierID, int CategoryID)
        {
            SqlDataProvider objSQL = new SqlDataProvider();
            DataTable objBind = objSQL.FillTable("Pro_Products_List", new ObjectPara("@Keyword", Keyword.Trim()), new ObjectPara("@SupplierID", SupplierID), new ObjectPara("@CategoryID", CategoryID));
            return objBind;
        }

        #endregion

        #region "GridView Methods"

        protected void grvObject_RowDataBound(object sender, System.Web.UI.WebControls.GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.Header)
            {
                string sSQL = "Select distinct Suppliers.SupplierID, Suppliers.CompanyName From Products INNER JOIN Suppliers on Products.SupplierID = Suppliers.SupplierID";
                DropDownList ddlSupplier = (DropDownList)e.Row.FindControl("ddlSupplier");
                if (ddlSupplier != null)
                {
                    LoadDropDownList(ddlSupplier, "SupplierID", "CompanyName", sSQL);
                    if (ViewState["Filter_Supplier"] != null)
                    {
                        ddlSupplier.Items.FindByValue(ViewState["Filter_Supplier"].ToString()).Selected = true;
                    }
                }

                DropDownList ddlCategory = (DropDownList)e.Row.FindControl("ddlCategory");
                if (ddlCategory != null)
                {
                    sSQL = "Select distinct Categories.CategoryID, Categories.CategoryName From Products INNER JOIN Categories on Products.CategoryID = Categories.CategoryID";
                    LoadDropDownList(ddlCategory, "CategoryID", "CategoryName", sSQL);
                    if (ViewState["Filter_Category"] != null)
                    {
                        ddlCategory.Items.FindByValue(ViewState["Filter_Category"].ToString()).Selected = true;
                    }
                }
            }
        }

        protected void grvObject_PageIndexChanging(object sender, System.Web.UI.WebControls.GridViewPageEventArgs e)
        {
            grvObject.PageIndex = e.NewPageIndex;
            BindProducts();
        }

        #endregion

        #region "Event Handles"

        protected void Page_Load(object sender, System.EventArgs e)
        {
            try
            {
                if (!IsPostBack)
                {
                    //Default Submit Button
                    Page.Form.DefaultButton = cmdQuickSearch.UniqueID;
                    BindProducts();
                }
            }
            catch
            {
            }
        }

        protected void cmdQuickSearch_Click(object sender, System.EventArgs e)
        {
            BindProducts();
        }

        protected void SupplierChanged(object sender, EventArgs e)
        {
            DropDownList ddlSupplier = (DropDownList)sender;
            if (ddlSupplier != null)
            {
                ViewState["Filter_Supplier"] = ddlSupplier.SelectedValue;
            }
            BindProducts();
        }

        protected void CategoryChanged(object sender, EventArgs e)
        {
            DropDownList ddlCategory = (DropDownList)sender;
            if (ddlCategory != null)
            {
                ViewState["Filter_Category"] = ddlCategory.SelectedValue;
            }
            BindProducts();
        }

        #endregion
    }
}

VB.NET Code

Namespace FilterRecordsUsingDropDownListInHeaderTemplate

    Public Class _Default
        Inherits System.Web.UI.Page

#Region "ComboData"

        Private Sub LoadDropDownList(ByVal ucControl As DropDownList, ByVal DataValueField As String, ByVal DataTextField As String, ByVal sql As String)
            Dim objSQL As New SqlDataProvider
            Dim objBind As DataTable = objSQL.FillTable(sql)

            ucControl.Items.Clear()

            If Not objBind Is Nothing Then
                With ucControl
                    .DataTextField = DataTextField
                    .DataValueField = DataValueField
                    .DataSource = objBind
                    .DataBind()
                End With
                ucControl.Items.Insert(0, (New ListItem("---All---", "-1")))
            End If
        End Sub

#End Region

#Region "Bind Data"

        Private Sub BindProducts()
            Dim objBind As New DataTable
            Dim iTotal As Integer = 0
            Dim SupplierID As Integer = -1
            Dim CategoryID As Integer = -1

            If Not ViewState("Filter_Supplier") Is Nothing Then
                SupplierID = ViewState("Filter_Supplier")
            End If

            If Not ViewState("Filter_Category") Is Nothing Then
                CategoryID = ViewState("Filter_Category")
            End If

            objBind = BindData(txtSearch.Text, SupplierID, CategoryID)

            If Not objBind Is Nothing Then
                If objBind.Rows.Count > 0 Then
                    iTotal = objBind.Rows.Count
                    grvObject.DataSource = objBind
                    grvObject.DataBind()
                    trMessage.Visible = False
                    lblTotal.Visible = True
                    lblTotal.Text = "Total " & iTotal & " records"
                Else
                    trMessage.Visible = True
                    lblTotal.Visible = False
                    grvObject.DataSource = New List(Of String)
                    grvObject.DataBind()
                End If
                updatePanel.Update()
            End If
        End Sub

        Private Function BindData(ByVal Keyword As String, ByVal SupplierID As Integer, ByVal CategoryID As Integer) As DataTable
            Dim objSQL As New SqlDataProvider
            Dim objBind As DataTable = objSQL.FillTable("Pro_Products_List", New ObjectPara("@Keyword", Keyword.Trim), _
                                                                            New ObjectPara("@SupplierID", SupplierID), _
                                                                            New ObjectPara("@CategoryID", CategoryID))
            Return objBind
        End Function

#End Region

#Region "GridView Methods"

        Private Sub grvObject_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles grvObject.RowDataBound
            If (e.Row.RowType = DataControlRowType.Header) Then
                Dim sSQL As String = "Select distinct Suppliers.SupplierID, Suppliers.CompanyName From Products INNER JOIN Suppliers on Products.SupplierID = Suppliers.SupplierID"
                Dim ddlSupplier As DropDownList = CType(e.Row.FindControl("ddlSupplier"), DropDownList)
                If Not ddlSupplier Is Nothing Then
                    LoadDropDownList(ddlSupplier, "SupplierID", "CompanyName", sSQL)
                    If Not ViewState("Filter_Supplier") Is Nothing Then
                        ddlSupplier.Items.FindByValue(ViewState("Filter_Supplier").ToString()).Selected = True
                    End If
                End If

                Dim ddlCategory As DropDownList = CType(e.Row.FindControl("ddlCategory"), DropDownList)
                If Not ddlCategory Is Nothing Then
                    sSQL = "Select distinct Categories.CategoryID, Categories.CategoryName From Products INNER JOIN Categories on Products.CategoryID = Categories.CategoryID"
                    LoadDropDownList(ddlCategory, "CategoryID", "CategoryName", sSQL)
                    If Not ViewState("Filter_Category") Is Nothing Then
                        ddlCategory.Items.FindByValue(ViewState("Filter_Category").ToString()).Selected = True
                    End If
                End If
            End If
        End Sub

        Private Sub grvObject_PageIndexChanging(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewPageEventArgs) Handles grvObject.PageIndexChanging
            grvObject.PageIndex = e.NewPageIndex
            BindProducts()
        End Sub

#End Region

#Region "Event Handles"

        Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
            Try
                If Page.IsPostBack = False Then
                    'Default Submit Button
                    Page.Form.DefaultButton = cmdQuickSearch.UniqueID
                    BindProducts()
                End If
            Catch ex As Exception

            End Try
        End Sub

        Private Sub cmdQuickSearch_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles cmdQuickSearch.Click
            BindProducts()
        End Sub

        Protected Sub SupplierChanged(ByVal sender As Object, ByVal e As EventArgs)
            Dim ddlSupplier As DropDownList = DirectCast(sender, DropDownList)
            If Not ddlSupplier Is Nothing Then
                ViewState("Filter_Supplier") = ddlSupplier.SelectedValue
            End If
            BindProducts()
        End Sub

        Protected Sub CategoryChanged(ByVal sender As Object, ByVal e As EventArgs)
            Dim ddlCategory As DropDownList = DirectCast(sender, DropDownList)
            If Not ddlCategory Is Nothing Then
                ViewState("Filter_Category") = ddlCategory.SelectedValue
            End If
            BindProducts()
        End Sub

#End Region

    End Class

End Namespace

Bây giờ chạy Project bạn sẽ có kết quả như ảnh phía dưới.

Code Example C#, Code Example VB.NET
Code Example C#, Code Example VB.NET



Chúc các bạn thành công!

Quang Bình

Share This:

Mỗi bài viết đều là công sức và thời gian của tác giả ví vậy tác giả chỉ có một mong muốn duy nhất nếu ai đó có Copy thì xin hãy ghi rõ nguồn và thông tin tác giả ở cuối mỗi bài viết.
Xin cảm ơn!

No Comment to " Sử dụng Dropdownlist để lọc dữ liệu trong Gridview HeaderTemplate "

  • To add an Emoticons Show Icons
  • To add code Use [pre]code here[/pre]
  • To add an Image Use [img]IMAGE-URL-HERE[/img]
  • To add Youtube video just paste a video link like http://www.youtube.com/watch?v=0x_gnfpL3RM