(Using Bootstrap to change DropDownList style in ASP.Net) – Theo mặc định khi lựa chọn giá trị trong danh sách Dropdownlist, chương  trình sẽ không đánh dấu giá trị nào đã được người dùng đã chọn. Chính việc  này sẽ gây khó khăn cho người dùng khi sửa và chọn lại giá trị trong Dropdownlist. Bài viết dưới đây sẽ hướng dẫn các bạn cách thay đổi Style để Dropdownlist trông đẹp và chuyên nghiệp hơn, ngoài ra đối với giá trị đã được chọn sẽ được đánh dấu giúp người dùng dễ dàng quan sát hơn.


Nghe những bài hát đỉnh nhất về Thấy cô giáo - Nghe trên Youtube



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



- B1: Download CSDL Northwind  tại đây và thực hiện công việc Restore Data.

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 UsingBootstrapChangeDropdownlistStyle
{
    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 UsingBootstrapChangeDropdownlistStyle

    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 StringAs 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 file bootstrap-select.css -> Copy vào thư mục Styles

- B4: Download file bootstrap-select.js -> Copy vào thư mục Js

B5: 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>Using BootStrap to change DropDownList style in ASP.Net</title>
    <link href="~/Styles/Site.css"rel="stylesheet"type="text/css"/>
    <link rel="stylesheet"href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css"/>
    <link rel="stylesheet"href="Styles/bootstrap-select.css"/>
    <script type="text/javascript"src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
    <script type="text/javascript"src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>
    <script type="text/javascript"src="Js/bootstrap-select.js"></script>
    <asp:ContentPlaceHolderID="HeadContent"runat="server">
    </asp:ContentPlaceHolder>
</head>

B6: Mở file Default.aspx dưới dạng HTML và  nhập mã HTML
<%@ PageTitle="Using Bootstrap to change DropDownList style in ASP.Net" Language="C#"MasterPageFile="~/Site.master"AutoEventWireup="true"CodeBehind="Default.aspx.cs"Inherits="UsingBootstrapChangeDropdownlistStyle._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>
       Using Bootstrap to change DropDownList style in ASP.Net
    </h4>
    <br />
    <asp:UpdatePanel ID="updatePanel"runat="server"UpdateMode="Conditional">
        <ContentTemplate>
            <table cellpadding="0"cellspacing="0"width="60%">
                <tr>
                    <td>Category:
                        <asp:DropDownList ID="ddlObject" runat="server" Width="320px" class="selectpicker show-tick">
                        </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 UsingBootstrapChangeDropdownlistStyle
{
    public partial class _Default : System.Web.UI.Page
    {

        #region"Bind Data"

        private voidPopulateDropdownlist()
        {
            DataTable objBind = newDataTable();
            int CategoryID = -1;
            string CategoryName = "";
            string TotalProducts = "";

            objBind = BindData();

            if (objBind != null)
            {
                if (objBind.Rows.Count > 0)
                {
                    for(int i = 0; i <= objBind.Rows.Count - 1; i++)
                    {
                        if (objBind.Rows[i]["CategoryID"] != null)
                        {
                            CategoryID =Convert.ToInt32(objBind.Rows[i]["CategoryID"]);
                        }
                        if (objBind.Rows[i]["CategoryName"] != null)
                        {
                            CategoryName = objBind.Rows[i]["CategoryName"].ToString();
                        }
                        if(objBind.Rows[i]["TotalProducts"] != null)
                        {
                            TotalProducts = objBind.Rows[i]["TotalProducts"].ToString();
                        }
                        ddlObject.Items.Add(new ListItem(CategoryName + " (" + TotalProducts + ")", CategoryID.ToString()));
                    }
                }
            }
        }

        private DataTableBindData()
        {
            SqlDataProvider objSQL = newSqlDataProvider();

            DataTable objBind = objSQL.FillTable("Select Products.CategoryID, Categories.CategoryName, COUNT(Products.ProductID) AS TotalProducts FROM Products INNER JOIN Categories ON Products.CategoryID = Categories.CategoryID GROUP BY Products.CategoryID, Categories.CategoryName ORDER BY Categories.CategoryName");
            return objBind;
        }

        #endregion

        #region"Event Handles"

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

        #endregion
    }
}
VB.NET Code
'Visit http://www.laptrinhdotnet.com for more ASP.NET Tutorials

Namespace UsingBootstrapChangeDropdownlistStyle

    Public Class _Default
        Inherits System.Web.UI.Page

#Region "Bind Data"

        Private SubPopulateDropdownlist()
            Dim objBind As New DataTable
            Dim CategoryID As Integer = -1
            Dim CategoryName As String = ""
            Dim TotalProducts As String = ""

            objBind = BindData()

            If Not objBind Is Nothing Then
                If objBind.Rows.Count > 0 Then
                    For i AsInteger = 0 ToobjBind.Rows.Count - 1
                        If NotIsDBNull(objBind.Rows(i).Item("CategoryID")) Then
                            CategoryID = objBind.Rows(i).Item("CategoryID").ToString
                        End If
                        If NotIsDBNull(objBind.Rows(i).Item("CategoryName")) Then
                            CategoryName = objBind.Rows(i).Item("CategoryName").ToString
                        End If
                        If NotIsDBNull(objBind.Rows(i).Item("TotalProducts")) Then
                            TotalProducts = objBind.Rows(i).Item("TotalProducts").ToString
                        End If
                        With ddlObject
                            .Items.Add(New ListItem(CategoryName & " (" & TotalProducts & ")", CategoryID))
                        End With
                    Next
                End If
            End If
        End Sub

        Private FunctionBindData() As DataTable
            Dim objSQL As New SqlDataProvider

            Dim objBind As DataTable = objSQL.FillTable("Select Products.CategoryID, Categories.CategoryName, COUNT(Products.ProductID) AS TotalProducts FROM Products INNER JOIN Categories ON Products.CategoryID = Categories.CategoryID GROUP BY Products.CategoryID, Categories.CategoryName ORDER BY Categories.CategoryName")
            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
                    PopulateDropdownlist()
                End If
            Catch ex As Exception

            End Try
        End Sub

#End Region

    End Class

End Namespace
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

0 comments Blogger 0 Facebook

Post a Comment

 
lập trình đốt nét © 2013. All Rights Reserved. Powered by Blogger
Top