Bind Asp.Net DropDownList and Disable or make some items Unselectable based on condition

Bind dropdownlist dynamically from sql server database and disable some items based on conditionIntroduction: In this article, using Asp.Net with both C# and VB Languages  I am going to explain How to dynamically Bind/Populate/Fill DropDownList  from Sql Server Database table and how to disable or making some items non-selectable based on condition so that user can't select them.


Description:  While working on asp.net project I got the requirement to populate departments in DropDownList and disable some of the departments in the Dropdownlist so that they can't be selected. The solution was easy. We just need to loop through all the items of the DropDownList and disable the items based on whatever condition we want. E.g. here in this article I have disabled the Admin and Finance departments.

Implementation:  Let's create a simple website page (default.aspx) to demonstrate the concept.

First of all create a table in the Sql server database with the columns names and data type as shown below and name it "Dept_Master"

Columns Name
Data Type
DeptId
Int(Primary Key. Auto Increment)
DeptName
varchar(100)

And insert some department names in this table. 
  • Now In the Web.config file create the connection string as:

<connectionStrings>
 <add name="conStr" connectionString="Data Source=YourDataSource;Initial Catalog=YourDatabasename;Integrated Security=True"/>
 </connectionStrings>

  • In the default. aspx page place a DropDownList controls as:
<fieldset style="width: 270px;">
            <legend>Fill DropDownList and Disable Items</legend>
            <asp:DropDownList ID="ddlDepartments" runat="server">
            </asp:DropDownList>
        </fieldset>


Asp.Net C# Code to Fill/Bind/populate DropDownList and Disable specified items

First include required namespaces

using System.Data;
using System.Data.SqlClient;
using System.Configuration;

Then write the code as:
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            FillDropDownListAndDisableItems();
        }
    }

    protected void FillDropDownListAndDisableItems()
    {
        SqlCommand cmd = new SqlCommand();
        SqlConnection con = new SqlConnection();
        SqlDataReader dr = null;
        try
        {
            con = new SqlConnection(ConfigurationManager.ConnectionStrings["conStr"].ConnectionString);
            cmd = new SqlCommand("Select * from Dept_Master", con);
            if (con.State==ConnectionState.Closed)
            {
             con.Open();
            }           
            dr = cmd.ExecuteReader();
            if (dr.HasRows)
            {
                ddlDepartments.DataSource = dr;
                ddlDepartments.DataTextField = "DeptName";
                ddlDepartments.DataValueField = "DeptId";
                ddlDepartments.DataBind();
                ddlDepartments.Items.Insert(0, new ListItem("--Select Department--", "-1"));      

                //Disable dropdownlist items based on condition
                foreach (ListItem item in ddlDepartments.Items)
                {
                    //Check by item value
                    //if (item.Value == "2" || item.Value == "4")
                    //OR Check by item text
                    if (item.Text == "Admin" || item.Text == "Finance")
                    {
                        item.Attributes.Add("disabled", "disabled");
                    }
                }
            }
            else
            {
                ddlDepartments.Items.Insert(0, "--No Departments--");
            }
        }

        catch (Exception ex)
        {
            Response.Write("Oops!! Error occured:" + ex.Message.ToString());
        }
        finally
        {           
            con.Close();          
            cmd.Dispose();
            dr.Dispose();
        }
    }


Asp.Net VB Code to Fill/Bind/populate DropDownList and Disable specified items

First include required namespaces

Imports System.Data
Imports System.Data.SqlClient
Imports System.Configuration

Then write the code as:

    Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
        If Not Page.IsPostBack Then
            FillDropDownListAndDisableItems()
        End If
    End Sub

    Protected Sub FillDropDownListAndDisableItems()
        Dim cmd As New SqlCommand()
        Dim con As New SqlConnection()
        Dim dr As SqlDataReader = Nothing
        Try
            con = New SqlConnection(ConfigurationManager.ConnectionStrings("conStr").ConnectionString)
            cmd = New SqlCommand("Select * from Dept_Master", con)
            If con.State = ConnectionState.Closed Then
                con.Open()
            End If
            dr = cmd.ExecuteReader()
            If dr.HasRows Then
                ddlDepartments.DataSource = dr
                ddlDepartments.DataTextField = "DeptName"
                ddlDepartments.DataValueField = "DeptId"
                ddlDepartments.DataBind()
                ddlDepartments.Items.Insert(0, New ListItem("--Select Department--", "-1"))

                'Disable dropdownlist items based on condition
                For Each item As ListItem In ddlDepartments.Items
                    'Check by item value
                    'if (item.Value == "2" || item.Value == "4")
                    'OR Check by item text
                    If item.Text = "Admin" OrElse item.Text = "Finance" Then
                        item.Attributes.Add("disabled", "disabled")
                    End If
                Next
            Else
                ddlDepartments.Items.Insert(0, "--No Departments--")
            End If

        Catch ex As Exception
            Response.Write("Oops!! Error occured:" & ex.Message.ToString())
        Finally
            con.Close()
            cmd.Dispose()
            dr.Dispose()
        End Try

    End Sub

Now over to you:
" I hope you have learned how to Bind Asp.Net DropDownList and Disable or make some items Un-selectable based on condition with this example and If you like my work; you can appreciate by leaving your comments, hitting Facebook like button, following on Google+, Twitter, Linked in and Pinterest, stumbling my posts on stumble upon and subscribing for receiving free updates directly to your inbox . Stay tuned and stay connected for more technical updates."
Previous
Next Post »

2 comments

Click here for comments
Anonymous
admin
September 02, 2014 ×

please Explain this part...........
-------------------------------------------------------------------------------------------------------------
if (dr.HasRows)
{
ddlDepartments.DataSource = dr;
ddlDepartments.DataTextField = "DeptName";
ddlDepartments.DataValueField = "DeptId";
ddlDepartments.DataBind();
ddlDepartments.Items.Insert(0, new ListItem("--Select Department--", "-1"));
------------------------------------------------------------------------------------------------------------------

Reply
avatar
September 02, 2014 ×

Here we are checking whether datareader has data in it or not..If it has data then we are binding the data to dropdownlist. DeptName will be displayed in the dropdownlist and DeptId will be used internally so that you can get the selected value and save in database.. In the last line we are inserting --Select Department-- which will be displayed as the very first item.

Reply
avatar

If you have any question about any post, Feel free to ask.You can simply drop a comment below post or contact via Contact Us form. Your feedback and suggestions will be highly appreciated. Also try to leave comments from your account not from the anonymous account so that i can respond to you easily..