(Multiple Select DropDownList with CheckBoxes in Asp.net) – Mặc định Dropdowlist chỉ cho phép người sử dụng lựa chọn 1 giá trị trong danh sách. Nếu cần sử dụng chức năng lọc hoặc thêm đồng thời nhiều giá trị khi được chọn người sử dụng Control Checkboxlist. Tuy nhiên khi sử dụng Control này sẽ tốn nhiều diện tích trên Form khi có nhiều giá trị trong danh sách. Vậy có Control nào cách hiển thị giống DropdownList và có thể chọn được đồng thời nhiều giá trị không? Bài viết dưới đây sẽ hướng dẫn các bạn sử dụng Control ListBox và cho phép người sử dụng chọn nhiều giá trị đồng thời.
- B2: Tạo stored procedure trong SQL Server
CREATE PROCEDURE [dbo].[Pro_Categories_List]
@Keyword nvarchar(250)
AS
declare@strSQL nvarchar(1000)
declare @strWhere nvarchar(500)
declare @strOrder nvarchar (50)
set @strSQL= 'SELECT CategoryID,CategoryName from Categories'
set @strWhere =' Where 1=1 '
if @Keyword<>''
set @strWhere= @strWhere +' And (CategoryName like N''%' +@Keyword+'%'' )'
set @strOrder =' Order by CategoryName'
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.
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 MultiSelectDropdownlist
{
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 DataTableFillTable(string ProcName, params ObjectPara[] Para)
{
try
{
DataTable tb = new DataTable();
SqlDataAdapter adap = new SqlDataAdapter(ProcName, _connectionString);
adap.SelectCommand.CommandType = CommandType.StoredProcedure;
if (Para != null)
{
foreach (ObjectParap in Para)
{
adap.SelectCommand.Parameters.Add(new SqlParameter(p.Name, p.Value));
}
}
adap.Fill(tb);
return tb;
}
catch
{
return null;
}
}
#endregion
}
public class ObjectPara
{
string _name;
object _Value;
public ObjectPara(stringPname, object PValue)
{
_name = Pname;
_Value = PValue;
}
public string Name
{
get { return _name; }
set { _name = value; }
}
public object Value
{
get { return _Value; }
set { _Value = value; }
}
}
}
VB.NET Code
Imports System.Data.SqlClient
Imports System.Data
Namespace MultiSelectDropdownlist
Public Class SqlDataProvider
#Region "Membres Prives"
Shared _IsError As Boolean = False
Private _connectionString AsString
#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() AsString
Get
Return _connectionString
End Get
End Property
#End Region
#Region "Functions"
Public FunctionFillTable(ByVal ProcName As String, ByVal ParamArrayPara() As ObjectPara) As DataTable
Try
Dim tb AsNew DataTable
Dim adap AsNew SqlDataAdapter(ProcName, _connectionString)
adap.SelectCommand.CommandType = CommandType.StoredProcedure
If NotPara Is NothingThen
ForEach 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 PropertyName() As String
Get
Return _name
End Get
Set(ByVal value As String)
_name = value
End Set
End Property
Public PropertyValue() As Object
Get
Return _Value
End Get
Set(ByVal value As Object)
_Value = value
End Set
End Property
End Class
End Namespace
- B4: Download các file bootstrap-multiselect.js, bootstrap-multiselect.css lần lượt copy vào các thư mục Js và Styles của Project.
- B5: Mở file Site.Master dạng HTML và bổ xung đoạn mã phía dưới trong thẻ Head
<link href="~/Styles/Site.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<link href="http://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.0.3/css/bootstrap.min.css"
rel="stylesheet" type="text/css" />
<script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.0.3/js/bootstrap.min.js"></script>
<!-- Include the plugin's CSS and JS: -->
<script type="text/javascript" src="js/bootstrap-multiselect.js"></script>
<link rel="stylesheet" href="Styles/bootstrap-multiselect.css" type="text/css"/>
- B6: Mở file Default.aspx dưới dạng HTML và nhập mã HTML
<%@ PageTitle="Multiple Select DropDownList with CheckBoxes in ASP.Net" Language="C#"MasterPageFile="~/Site.master"AutoEventWireup="true"CodeBehind="Default.aspx.cs"Inherits="MultiSelectDropdownlist._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>
<h4>
Multiple Select DropDownList with CheckBoxes in ASP.Net
</h4>
<br />
<asp:Literal ID="ltScript"runat="server"></asp:Literal>
<asp:UpdatePanel ID="updatePanel"runat="server"UpdateMode="Conditional">
<ContentTemplate>
<table cellpadding="0"cellspacing="0"width="60%">
<tr>
<td>
<asp:ListBox ID="ddlObject"runat="server"SelectionMode="Multiple">
</asp:ListBox>
<asp:LinkButton id="cmdSubmit" runat="server" Text="Submit" OnClick="cmdSubmit_Click" Causesvalidation="true">
</asp:LinkButton>
</td>
</tr>
<tr>
<td>
<br /><asp:Label ID="lblMessage" runat="server"></asp:Label>
</td>
</tr>
</table>
</ContentTemplate>
</asp:UpdatePanel>
</asp:Content>
- B7: 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 MultiSelectDropdownlist
{
public partial class _Default : System.Web.UI.Page
{
#region"Bind Data"
private voidPopulateDropdownlist()
{
DataTable objBind = newDataTable();
objBind = BindData();
if (objBind != null)
{
if (objBind.Rows.Count > 0)
{
ddlObject.DataTextField = "CategoryName";
ddlObject.DataValueField = "CategoryID";
ddlObject.DataSource = objBind;
ddlObject.DataBind();
}
}
}
private DataTableBindData()
{
SqlDataProvider objSQL = newSqlDataProvider();
DataTable objBind = objSQL.FillTable("Pro_Categories_List", new ObjectPara("@Keyword", ""));
return objBind;
}
#endregion
#region"Bind Data"
private voidWriteJava()
{
string sJava = "";
//Caching
if (Cache["Cache_MultiSelect"] == null)
{
sJava += "<script type=\"text/javascript\">";
sJava += " function pageLoad() {";
sJava += " $('[id*=ddlObject]').multiselect({";
sJava += " includeSelectAllOption: true" ;
sJava += " });" ;
sJava += " };" ;
sJava += "</script>";
Cache["Cache_MultiSelect"] = sJava;
}
else
{
sJava = Convert.ToString(Cache["Cache_MultiSelect"]);
}
ltScript.Text = sJava;
}
#endregion
#region"Event Handles"
protected voidPage_Load(object sender, System.EventArgs e)
{
try
{
if (!IsPostBack)
{
WriteJava();
PopulateDropdownlist();
}
}
catch
{
}
}
protected voidcmdSubmit_Click(object sender, System.EventArgs e)
{
string sMessage = "";
foreach (ListItemitem in ddlObject.Items)
{
if (item.Selected)
{
sMessage += item.Text + "-"+ item.Value + "<br />";
}
}
if (!string.IsNullOrEmpty(sMessage))
{
lblMessage.Text = "<b>Selected:</b><br />" + sMessage;
}
}
#endregion
}
}
VB.NET Code
'Visit http://www.laptrinhdotnet.com for more ASP.NET Tutorials
Namespace MultiSelectDropdownlist
Public Class _Default
Inherits System.Web.UI.Page
#Region "Bind Data"
Private SubPopulateDropdownlist()
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 FunctionBindData() As DataTable
Dim objSQL As New SqlDataProvider
Dim objBind As DataTable = objSQL.FillTable("Pro_Categories_List", New ObjectPara("@Keyword", ""))
Return objBind
End Function
#End Region
#Region "Javascript"
Private SubWriteJava()
Dim sJava As String = ""
'Caching
If Cache("Cache_MultiSelect") Is Nothing Then
sJava &= "<script type=""text/javascript"">" & vbCrLf
sJava &= " function pageLoad() {" & vbCrLf
sJava &= " $('[id*=ddlObject]').multiselect({" & vbCrLf
sJava &= " includeSelectAllOption: true" & vbCrLf
sJava &= " });" & vbCrLf
sJava &= " };" & vbCrLf
sJava &= "</script>"& vbCrLf
Cache("Cache_MultiSelect") = sJava
Else
sJava = CType(Cache("Cache_MultiSelect"), String)
End If
ltScript.Text = sJava
End Sub
#End Region
#Region "Event Handles"
Protected SubPage_Load(ByVal sender AsObject, ByVal e As System.EventArgs) Handles Me.Load
Try
If Page.IsPostBack = False Then
WriteJava()
PopulateDropdownlist()
End If
Catch ex As Exception
End Try
End Sub
Private SubcmdSubmit_Click(ByVal sender As Object, ByVal e As System.EventArgs) HandlescmdSubmit.Click
Dim sMessage As String = ""
If ddlObject.Items.Count > 0 Then
For Eachitem As ListItemIn ddlObject.Items
If item.Selected Then
sMessage &= item.Text & "-" & item.Value & "<br />"
End If
Next
End If
If sMessage <> ""Then
lblMessage.Text = "<b>Selected:</b><br />" & 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.
Chúc các bạn thành công!
Quang Bình
0 comments Blogger 0 Facebook
Post a Comment