Related Posts Plugin for WordPress, Blogger...

About

Follow Us

Tuesday 17 February 2015

Introduction:

Sometime it is required to fill dropdown and disable its some of the items on the basis of some condtion. While working on one of my asp.net project I got the requirement to populate departments in DropDownList and disable some of them so that they can't be selected.
Suppose if Department Name is “HRM” then it got disable.



In this article, I have explained how to dynamically Fill Dropdown List from SQL
Server Database table and how to disable or making some items non-selectable based on condition.
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
Dept_Id_Pk
Int(Primary Key. Auto Increment)
Dept_Name
varchar(100)

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

<connectionStrings>
 <add name="Empcon" connectionString="Data Source=localhost;Initial Catalog=test;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  DropDownList and Disable specified items
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["Empcon"].ConnectionString);
            cmd = new SqlCommand("Select * from Dept_Table", con);
            if (con.State==ConnectionState.Closed)
            {
             con.Open();
            }           
            dr = cmd.ExecuteReader();
            if (dr.HasRows)
            {
                ddlDepartments.DataSource = dr;
                ddlDepartments.DataTextField = "Dept_Name";
                ddlDepartments.DataValueField = "Dept_Id_pk";
                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 == "HRM" || item.Text == "Test")
                    {
                        item.Attributes.Add("disabled", "disabled");
                    }
                }
            }
            else
            {
                ddlDepartments.Items.Insert(0, "--No Departments--");
            }
        }

        catch (Exception ex)
        {
            Response.Write(“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

Include required namespaces
Imports System.Data
Imports System.Data.SqlClient
Imports System.Configuration

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("EmpCon").ConnectionString)
            cmd = New SqlCommand("Select * from Dept_Table", con)
            If con.State = ConnectionState.Closed Then
                con.Open()
            End If
            dr = cmd.ExecuteReader()
            If dr.HasRows Then
                ddlDepartments.DataSource = dr
                ddlDepartments.DataTextField = "Dept_Name"
                ddlDepartments.DataValueField = "Dept_Id_pk"
                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 = "HRM" OrElse item.Text = "Testing" Then
                        item.Attributes.Add("disabled", "disabled")
                    End If
                Next
            Else
                ddlDepartments.Items.Insert(0, "--No Departments--")
            End If

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


    End Sub

0 comments:

Post a Comment