News Ticker

Menu

Jquery Multiselect DropDownList with CheckBoxes in ASP.Net

(Multiple Select DropDownList with CheckBoxes in ASP.Net) – Để giải quyết vấn đề cho phép chọn nhiều giá trị đồng thời bạn thường sử dụng Control Checkboxlist trong trường hợp có ít giá trị trong danh sách. Nếu danh sách có nhiều khi sử dụng Control Checkboxlist sẽ mất nhiều không gian trên Form. Hoặc bạn có thể sử dụng Duallistcontrol, tuy nhiên với Control này người sử dụng sẽ mất thêm thao tác chọn các giá trị và chuyển. Vậy có giải pháp nào tối ưu cho thao tác chọn nhiều giá trị  trong danh sách đồng thời không? Bài viết dưới đây sẽ hướng dẫn các bạn sử dụng Control DropDownList và cho phép người sử dụng chọn nhiều giá trị đồng thời.
Code Example C#, Code Example VB.NET
Code Example C#, Code Example VB.NET


B1Download CSDL Northwind

B2: 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.
C# Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;

namespace JqueryMultipleSelectDropdownlist
{
    public class SqlDataProvider
    {
        #region "Membres Prives"

        private string _connectionString;

        #endregion

        #region "Constructeurs"

        public SqlDataProvider()
        {
            try
            {
                _connectionString = ConfigurationManager.ConnectionStrings["SiteSqlServer"].ConnectionString;
            }
            catch
            {
            }
        }

        #endregion

        #region "Proprietes"

        public string ConnectionString
        {
            get { return _connectionString; }
        }

        #endregion

        #region "Functions"

        public DataTable FillTable(string sql)
        {
            try
            {
                DataTable tb = new DataTable();
                SqlDataAdapter adap = new SqlDataAdapter(sql, _connectionString);
                adap.Fill(tb);
                return tb;
            }
            catch
            {
                return null;
            }
        }
        #endregion
    }
}
VB.NET Code
Imports System.Data.SqlClient
Imports System.Data

Namespace JqueryMultipleSelectDropdownlist

    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

#End Region

    End Class

End Namespace

- B3: Download thư viện jquery-ui-multiselect-widget  tại đây.

- B4: Copy các file Jquery.multiselect.css, Jquery.multiselect.filter.css vào thư mục Styles của Project.

- B5: Copy các file Jquery.multiselect.js, Jquery.multiselect.filter.js copy vào thư mục Js của Project.

B6: Mở file Site.Master dạng HTML và bổ xung đoạn mã phía dưới trong thẻ Head
<head id="Head1" runat="server">
    <title>Jquery MultipleSelect Dropdownlist with CheckBoxes in ASP.Net</title>
    <link href="~/Styles/Site.css" rel="stylesheet" type="text/css" />
    <link rel="stylesheet" href="Styles/Jquery.multiselect.css" />
    <link rel="stylesheet" href="Styles/Jquery.multiselect.filter.css" />
    <link rel="stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1/themes/ui-lightness/jquery-ui.css" />
    <script src="http://code.jquery.com/jquery-1.9.1.min.js" type="text/javascript"></script>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1/jquery-ui.min.js"></script>
    <script type="text/javascript" src="Js/Jquery.multiselect.js"></script>
    <script type="text/javascript" src="JS/Jquery.multiselect.filter.js" ></script>
    <asp:ContentPlaceHolder ID="HeadContent" runat="server">
    </asp:ContentPlaceHolder>
</head>

B7: Mở file Default.aspx dưới dạng HTML và  nhập mã HTML
<%@ Page Title="Jquery MultipleSelect Dropdownlist with CheckBoxes in ASP.Net" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="JqueryMultipleSelectDropdownlist._Default" %>
<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
    <asp:ScriptManager ID="ScriptManager1" runat="server">
    </asp:ScriptManager>
    <div class="panel panel-default" style="width:60%;height:330px;">
        <div class="panel-heading">
            <h3>Jquery MultipleSelect Dropdownlist with CheckBoxes in ASP.Net</h3>
        </div>
        <div class="panel-body">
            <table cellpadding="0" cellspacing="0" width="100%">
                <tr>
                    <td>
                        <asp:DropDownList ID="ddlObject" runat="server" Width="250" multiple="multiple">
                        </asp:DropDownList>
                        <asp:HiddenField ID="hdnObject" runat="server" />
                        &nbsp;&nbsp;<asp:LinkButton id="cmdSubmit" runat="server" OnClick="cmdSubmit_Click" Text="Submit" Causesvalidation="true">
                        </asp:LinkButton>
                    </td>
                </tr>
                <tr>
                    <td>
                        <br /><asp:Label ID="lblMessage" runat="server"></asp:Label>
                    </td>
                </tr>
            </table>
        </div>
    </div>
    <script type="text/javascript">
        function pageLoad() {
            $('#<%= ddlObject.ClientID %>').multiselect({
                header: '',
                close: function (event, ui) {
                    var arrObject = $('#<%= ddlObject.ClientID %>').multiselect("getChecked").map(function () {
                        return this.value;
                    }).get();
                    $('#<%= hdnObject.ClientID %>').val(arrObject);
                }
            }).multiselectfilter();

            if ($('#<%= hdnObject.ClientID %>').val() != '') {
                var selected = $('#<%= hdnObject.ClientID %>').val().split(",");
                $("#<%=ddlObject.ClientID%> > option").each(function () {
                    if ($.inArray(this.value, selected) > -1) {
                        $(this).attr("selected", "selected");
                    }
                });
                $("#<%=ddlObject.ClientID%>").multiselect('refresh');
            }
        };
    </script>
</asp:Content>

B8: 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.IO;
using System.Diagnostics;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Caching;

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

        #region "Bind Data"

        private void PopulateDropdownlist()
        {
            DataTable objBind = new DataTable();
            objBind = BindData();

            if (objBind != null)
            {
                if (objBind.Rows.Count > 0)
                {
                    ddlObject.DataTextField = "CategoryName";
                    ddlObject.DataValueField = "CategoryID";
                    ddlObject.DataSource = objBind;
                    ddlObject.DataBind();
                }
            }
        }

        private DataTable BindData()
        {
            SqlDataProvider objSQL = new SqlDataProvider();

            DataTable objBind = objSQL.FillTable("Select CategoryID,CategoryName from Categories");
            return objBind;
        }

        #endregion

        #region "Event Handles"

        protected void Page_Load(object sender, System.EventArgs e)
        {
            try
            {
                if (!IsPostBack)
                {
                    PopulateDropdownlist();
                }
            }
            catch
            {
            }
        }

        protected void cmdSubmit_Click(object sender, System.EventArgs e)
        {
            string sMessage = "";
            sMessage = hdnObject.Value;
             if (!string.IsNullOrEmpty(sMessage))
             {
                  lblMessage.Text = "<b>Selected:</b> " + sMessage;
             }
        }

        #endregion
    }
}
VB.NET Code

'Visit http://www.laptrinhdotnet.com for more ASP.NET Tutorials

Namespace JqueryMultipleSelectDropdownlist

    Public Class _Default
        Inherits System.Web.UI.Page

#Region "Bind Data"

        Private Sub PopulateDropdownlist()
            Dim objBind As New DataTable

            objBind = BindData()

            If Not objBind Is Nothing Then
                If objBind.Rows.Count > 0 Then
                    With ddlObject
                        .DataTextField = "CategoryName"
                        .DataValueField = "CategoryID"
                    End With
                    ddlObject.DataSource = objBind
                    ddlObject.DataBind()
                End If
            End If
        End Sub

        Private Function BindData() As DataTable
            Dim objSQL As New SqlDataProvider

            Dim objBind As DataTable = objSQL.FillTable("Select CategoryID,CategoryName from Categories")
            Return objBind
        End Function

#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
                    PopulateDropdownlist()
                End If
            Catch ex As Exception

            End Try
        End Sub

        Private Sub cmdSubmit_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles cmdSubmit.Click
            Dim sMessage As String = ""
            sMessage = hdnObject.Value
            If sMessage <> "" Then
                lblMessage.Text = "<b>Selected:</b> " & sMessage
            End If
        End Sub

#End Region

    End Class

End Namespace

Bây giờ chạy Project bạn đã có thể lựa chọn 1 hoặc nhiều giá trị trong danh sách rồ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 " Jquery Multiselect DropDownList with CheckBoxes in ASP.Net "

  • 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