Hi Chriz,
Check this example. Now please take its reference and correct your code.
DataBase
For this example I have used of NorthWind database that you can download using the link given below.
Download Northwind Database
HTML
<asp:DropDownList ID="ddlNames" runat="server">
</asp:DropDownList>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
GroupDropdownlist('ddlNames')
});
function GroupDropdownlist(id) {
var selectControl = $('#' + id);
var groups = [];
$(selectControl).find('option').each(function () {
groups.push($(this).attr('data-group'));
});
var uniqueGroup = groups.filter(function (itm, i, a) {
return i == a.indexOf(itm);
});
$(uniqueGroup).each(function () {
var Group = jQuery('<optgroup/>', { label: $(this)[0] }).appendTo(selectControl);
var grpItems = $(selectControl).find('option[data-group="' + $(this)[0] + '"]');
$(grpItems).each(function () {
var item = $(this);
item.appendTo(Group);
});
});
}
</script>
Namespaces
C#
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
VB.Net
Imports System.Data.SqlClient
Imports System.Data
Code
C#
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
string str = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
SqlConnection conn = new SqlConnection(str);
conn.Open();
SqlCommand cmd = new SqlCommand("SELECT EmployeeID,FirstName,TitleOfCourtesy FROM Employees", conn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
foreach (DataRow row in dt.Rows)
{
ListItem item = new ListItem();
item.Text = row["FirstName"].ToString();
item.Value = row["EmployeeID"].ToString();
item.Attributes["data-group"] = row["TitleOfCourtesy"].ToString();
ddlNames.Items.Add(item);
}
conn.Close();
}
}
VB.Net
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
If Not Me.IsPostBack Then
Dim str As String = ConfigurationManager.ConnectionStrings("ConString").ConnectionString
Dim conn As SqlConnection = New SqlConnection(str)
conn.Open()
Dim cmd As SqlCommand = New SqlCommand("SELECT EmployeeID,FirstName,TitleOfCourtesy FROM Employees", conn)
Dim da As SqlDataAdapter = New SqlDataAdapter(cmd)
Dim dt As DataTable = New DataTable()
da.Fill(dt)
For Each row As DataRow In dt.Rows
Dim item As ListItem = New ListItem()
item.Text = row("FirstName").ToString()
item.Value = row("EmployeeID").ToString()
item.Attributes("data-group") = row("TitleOfCourtesy").ToString()
ddlNames.Items.Add(item)
Next
conn.Close()
End If
End Sub
Screenshot