-->

Thursday, March 24, 2016

DropdownList Selected Disabled Default item in ASP.NET C#

DropdownList Selected Disabled Default item in ASP.NET C#

In this article, I will show you, How to add default item at index 0 in DropdownList, also select default item, default item will be disabled when drop down the popup. For this task, first of all bind the DropdownList then you can add default item at index first by using following line of code:

      DropDownList1.Items.Insert(0, "Select");
After that you can select or disabled default item by the following line of code:
        DropDownList1.Items[0].Selected = true;
        DropDownList1.Items[0].Attributes["Disabled"] = "Disabled";
Source Code

<div>
    
        <asp:DropDownList ID="DropDownList1" runat="server">
        </asp:DropDownList>
    
    </div>

Code Behind Code

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Default9 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            binddrop();
        }
    }

    private void binddrop()
    {
        SqlConnection con = new SqlConnection();
        con.ConnectionString  =ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();
        con.Open();

        SqlCommand cmd = new SqlCommand();
        cmd.CommandText ="select * from [Employee]";
        cmd.Connection =con;

        SqlDataReader rd=  cmd.ExecuteReader();
        DropDownList1.DataSource =rd;
        DropDownList1.DataTextField = "Name";
        DropDownList1.DataValueField = "Id";
        DropDownList1.DataBind();

        DropDownList1.Items.Insert(0, "Select");
        DropDownList1.Items[0].Selected = true;
        DropDownList1.Items[0].Attributes["Disabled"] = "Disabled";


    }
}

Code generates the following output :


Read other related articles

Also read other articles

© Copyright 2013 Computer Programming | All Right Reserved