(Tạo danh sách đa cấp cho Dropdownlist trong Asp.net) – Khi bạn có 1 danh sách dữ liệu, danh sách này có nhiều cấp độ khác nhau. Bạn đang muốn thể hiện rõ ràng cấp độ trong danh sách chọn của Dropdownlist đó để người sử dụng dễ quan sát và lựa chọn hơn. Dưới đây là bài viết thủ thuật lập trình sẽ giới thiệu với các bạn các bước để có thể danh sách chọn đa cấp trong Dropdownlist.
- B1: Tạo CSDL SQL Customers
- B2: Tạo Bảng Categories có cấu trúc phía dưới trong CSDL SQL Server
STT | Tên trường | Kiểu trường | Ghi chú |
1 | CategoryID | Int | Trường tự tăng |
2 | ParentID | Int | |
3 | CategoryName | nvarchar(250) | |
4 | [Level] | Int | |
5 | SortOrder | Int | |
6 | CreatedDate | datetime |
- B3: Nhập dữ liệu cho bảng Categories
- B4: Tạo các stored procedure trong SQL Server
CREATE PROCEDURE [dbo].[Pro_Category_List]
@SortField nvarchar(20)
AS
declare@strSQL nvarchar(500)
declare @strWhere nvarchar(100)
declare @strOrder nvarchar (50)
set @strSQL= 'Select * from Categories'
set @strWhere =' where 1=1'
if @SortField='Order'
Begin
set@strOrder =' Order by SortOrder'
End
Else
Begin
set@strOrder =' Order by CategoryName'
End
set @strSQL=@strSQL+@strWhere+@strOrder
print @strSQL
exec sp_executesql @strSQL
- B5: 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 PopulateMultiLevelDropdown
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 sql AsString) As DataTable
Try
Dim tb AsNew DataTable
Dim adap AsNew SqlDataAdapter(sql, _connectionString)
adap.Fill(tb)
Return tb
Catch ex As Exception
Return Nothing
End Try
End Function
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
For Eachp As ObjectParaIn 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
- B6: Mở file Default.aspx dưới dạng HTML và nhập mã HTML
<%@ PageTitle="Populate a Multi Level Dropdownlist in ASP.Net" Language="vb" MasterPageFile="~/Site.Master" AutoEventWireup="false" CodeBehind="Default.aspx.vb" Inherits="PopulateMultiLevelDropdown._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>
<h1>
Populate a Multi Level Dropdownlist in ASP.Net
</h1>
<br />
<asp:UpdatePanel ID="updatePanel"runat="server"UpdateMode="Conditional">
<ContentTemplate>
<table cellpadding="0"cellspacing="0"width="60%">
<tr>
<td>
<asp:DropDownList ID="ddlCategory" runat="server" Width="250px">
</asp:DropDownList>
</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;
namespace PopulateMultiLevelDropdown
{
public partial class _Default : System.Web.UI.Page
{
#region "Bind Data"
private voidPopulateMultiLevelDropdown()
{
DataTable objBind = newDataTable();
objBind = BindData();
if (objBind != null)
{
if (objBind.Rows.Count > 0)
{
ddlCategory.DataTextField = "CategoryName";
ddlCategory.DataValueField = "CategoryID";
ddlCategory.DataSource = objBind;
ddlCategory.DataBind();
}
}
}
private DataTableBindData()
{
SqlDataProvider objSQL = newSqlDataProvider();
DataTable objBind = newDataTable();
DataRow dtRow = null;
DataTable objTemp = newDataTable();
int intCounter = 0;
string strIndent = "";
int CategoryID = -1;
string CategoryName = "";
int Level = 0;
objTemp = objSQL.FillTable("Pro_Category_List", new ObjectPara("@SortField", "Order"));
if (objTemp != null)
{
objBind.Columns.Add("CategoryID", System.Type.GetType("System.Int32"));
objBind.Columns.Add("CategoryName", System.Type.GetType("System.String"));
for (inti = 0; i <= objTemp.Rows.Count - 1; i++)
{
dtRow = objBind.NewRow();
if (objTemp.Rows[i]["CategoryID"] != null)
{
CategoryID =(int) objTemp.Rows[i]["CategoryID"];
}
if (objTemp.Rows[i]["CategoryName"] != null)
{
CategoryName = objTemp.Rows[i]["CategoryName"].ToString();
}
if (objTemp.Rows[i]["Level"] != null)
{
Level =(int) objTemp.Rows[i]["Level"];
}
strIndent = "";
if (Level > 0)
{
for (intCounter = 1; intCounter <= Level; intCounter++)
{
strIndent += "...";
}
}
dtRow["CategoryID"] = CategoryID;
dtRow["CategoryName"] = strIndent + CategoryName;
objBind.Rows.Add(dtRow);
}
}
return objBind;
}
#endregion
#region"Event Handles"
protected voidPage_Load(object sender, System.EventArgs e)
{
try
{
if (!IsPostBack)
{
PopulateMultiLevelDropdown();
}
}
catch
{
}
}
#endregion
}
}
VB.NET Code
Namespace PopulateMultiLevelDropdown
Public Class _Default
Inherits System.Web.UI.Page
#Region "Bind Data"
Private SubPopulateMultiLevelDropdown()
Dim objBind As New DataTable
objBind = BindData()
If Not objBind Is Nothing Then
If objBind.Rows.Count > 0 Then
With ddlCategory
.DataTextField = "CategoryName"
.DataValueField = "CategoryID"
End With
ddlCategory.DataSource = objBind
ddlCategory.DataBind()
End If
End If
End Sub
Private FunctionBindData() As DataTable
Dim objSQL As New SqlDataProvider
Dim objBind As New DataTable
Dim dtRow As DataRow
Dim objTemp As New DataTable
Dim intCounter As Integer
Dim strIndent As String = ""
Dim CategoryID As Integer = -1
Dim CategoryName As String = ""
Dim Level As Integer = 0
objTemp = objSQL.FillTable("Pro_Category_List", New ObjectPara("@SortField", "Order"))
If Not objTemp Is Nothing Then
With objBind.Columns
.Add("CategoryID", System.Type.GetType("System.Int32"))
.Add("CategoryName", System.Type.GetType("System.String"))
End With
For i AsInteger = 0 ToobjTemp.Rows.Count - 1
dtRow = objBind.NewRow()
If NotIsDBNull(objTemp.Rows(i).Item("CategoryID")) Then
CategoryID = objTemp.Rows(i).Item("CategoryID")
End If
If NotIsDBNull(objTemp.Rows(i).Item("CategoryName")) Then
CategoryName = objTemp.Rows(i).Item("CategoryName")
End If
If NotIsDBNull(objTemp.Rows(i).Item("Level")) Then
Level = objTemp.Rows(i).Item("Level")
End If
strIndent = ""
If Level > 0 Then
For intCounter = 1 To Level
strIndent += "..."
Next
End If
dtRow("CategoryID") = CategoryID
dtRow("CategoryName") = strIndent & CategoryName
objBind.Rows.Add(dtRow)
Next
End If
Return objBind
End Function
#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
PopulateMultiLevelDropdown()
End If
Catch ex As Exception
End Try
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.
Chúc các bạn thành công!
Quang Bình
0 comments Blogger 0 Facebook
Post a Comment