Populate Category and Sub-category in single dropdownlist in Asp.net using C#, VB.net - Free Asp.Net,MVC,AngularJs,Jquery,Javascript,Sql Server,WCF,Entity framework snippets and tutorial

Populate Category and Sub-category in single dropdownlist in Asp.net using C#, VB.net

In this article I am going to explain how to populate Category and Sub-category in single dropdownlist in Asp.net


Description:
In this example I am going to display the Country and State name in a single dropdownlist. To implement the functionality I have created 2 tables Tb_Country and Tb_State.
Populate Category and Sub-category in single dropdownlist in Asp.net using C#, VB.net


Insert some dummy records into tables.

Implementation:

HTML Markup of webform:
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
   <style>
       .dropdownlist
       {
           width:200px;
           border:1px solid #000;
           border-radius:5px;
           height:30px;
           font-weight:bold;
       }
   .ddlCategory
   {
       font-weight:bold;
      background-color: #9E9E9E;
    font-size: 16px;
    color:#fff;
   }
   .ddlSubCategory
   {
       margin-left:15px;
   }
   </style>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:DropDownList ID="DropDownList1" runat="server" CssClass="dropdownlist">
        </asp:DropDownList>
    </div>
    </form>
</body>
</html>

Import the namespace:
C# code:
using System.Data;
using System.Data.SqlClient;
using System.Configuration;

VB.net Code:
Imports System.Data
Imports System.Data.SqlClient
Imports System.Configuration

Populate the dropdownlist
Create a function to populate the dropdownlist and call it on page load event.
C# code:
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["connection"].ToString());

protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            Populatedropdown();
        }
        foreach (ListItem item in DropDownList1.Items)
        {

            if (item.Value.ToString() == "-1")
            {
                item.Attributes.Add("class", "ddlCategory");
                item.Attributes.Add("Disabled", "true");
            }
            else
            {
                item.Attributes.Add("class", "ddlSubCategory");
            }
        }      
    }
    public void Populatedropdown()
    {       
        try
        {
            SqlCommand cmd = new SqlCommand("SELECT StateName,ID,CountryId_Fk FROM Tb_State UNION SELECT UPPER(CountryName),-1,ID FROM Tb_Country ORDER BY CountryId_Fk,id", con);
            DataTable dt = new DataTable();
            SqlDataAdapter adp = new SqlDataAdapter();
            adp = new SqlDataAdapter(cmd);
            adp.Fill(dt);
            DropDownList1.DataSource = dt;
            DropDownList1.DataTextField = "StateName";
            DropDownList1.DataValueField = "ID";
            DropDownList1.DataBind();
            DropDownList1.Items.Insert(0,"--Select City--");
        }
        catch (Exception ex)
        {
            Response.Write(ex.Message.ToString());
        }      
    }

VB.net Code:
Private con As New SqlConnection(ConfigurationManager.ConnectionStrings("connection").ToString())

Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
        If Not IsPostBack Then
            Populatedropdown()
        End If
        For Each item As ListItem In DropDownList1.Items
            If item.Value.ToString() = "-1" Then
                item.Attributes.Add("class", "ddlCategory")
                item.Attributes.Add("Disabled", "true")
            Else
                item.Attributes.Add("class", "ddlSubCategory")
            End If
        Next
    End Sub
    Public Sub Populatedropdown()
        Try
            Dim cmd As New SqlCommand("SELECT StateName,ID,CountryId_Fk FROM Tb_State UNION SELECT UPPER(CountryName),-1,ID FROM Tb_Country ORDER BY CountryId_Fk,id", con)
            Dim dt As New DataTable()
            Dim adp As New SqlDataAdapter()
            adp = New SqlDataAdapter(cmd)
            adp.Fill(dt)
            DropDownList1.DataSource = dt
            DropDownList1.DataTextField = "StateName"
            DropDownList1.DataValueField = "ID"
            DropDownList1.DataBind()
            DropDownList1.Items.Insert(0, "--Select City--")
        Catch ex As Exception
            Response.Write(ex.Message.ToString())
        End Try
    End Sub

Now build, run the project and check the working example..

 DEMO:
Populate Category and Sub-category in single dropdownlist in Asp.net using C#, VB.net

   In this article we have learn how to fill category and Sub-category in single dropdownlist in asp.net using (C#, VB.net). I hope you enjoyed this article. Please post you comment, query and feedback about this article. You can like me on Facebook, Google+, Linkedin and Twitter via hit on Follow us Button and also can get update follow by Email.  

What do you think about this article?

If you found this article useful, please share and follow on Facebook, Twitter, Google Plus and other social media websites. To get free updates subscribe to newsletter. Please put your thoughts and feedback in comments section.

Share this

Share on FacebookTweet on TwitterPlus on Google+


EmoticonEmoticon