Asp.net DropDownList Server Control


DropDownList Control

A DropDownList is also commonly known as combo box. It can contain multiple data members, but unlike a normal list box the users can choose only one value from this control. Though the functionality of this DropDownList is much like a Single Row Select List Box, a DropDownList can save a lot of GUI space as it is rendered on a Single line and is expanded only when the user clicks on the Control.
   This DropDownList is provided as a Server Control in ASP .Net like many other controls. This DropDownList can be used to add data manually or even for dynamic binding with data base.

Example first

Example 1st:
Adding data in DropDownList using property(Items collection)

<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True">
        <asp:ListItem>---Select city---asp:ListItem>
        <asp:ListItem>Madhubaniasp:ListItem>
        <asp:ListItem>Darbhangaasp:ListItem>
        <asp:ListItem>New Delhiasp:ListItem>
    asp:DropDownList>

Example 2nd :

Adding data in DropDownList using DataBind(database)
Source code
<asp:DropDownList ID="DropDownList2" runat="server">
        asp:DropDownList>
Code File
protected void Page_Load(object sender, EventArgs e)
    {
        SqlConnection con = new SqlConnection("Trusted_connection=true;database=pubs");
        SqlDataAdapter da = new SqlDataAdapter("Select * from authors",con);
        DataSet ds = new DataSet();
        da.Fill(ds);
        DropDownList2.DataSource = ds;
        DropDownList2.DataTextField = "city";
        DropDownList2.DataBind();
    }
Example 3rd :
Source code]

<asp:DropDownList ID="DropDownList3" runat="server" AutoPostBack="True">
            <asp:ListItem>---Select city---asp:ListItem>
            <asp:ListItem>Madhubaniasp:ListItem>
            <asp:ListItem>Darbhangaasp:ListItem>
            <asp:ListItem>New Delhiasp:ListItem>
        asp:DropDownList>
        <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Ok"
            Width="96px" />
        <asp:Label ID="Label1" runat="server">asp:Label>

Code File
protected void Button1_Click(object sender, EventArgs e)
    {
       Label1 .Text ="You have selected "+ DropDownList3.SelectedItem.Text;
    }

Example 4th :

Source code
<asp:DropDownList ID="DropDownList4" runat="server" AutoPostBack="True"
            onselectedindexchanged="DropDownList4_SelectedIndexChanged">
            <asp:ListItem>---Select city---asp:ListItem>
            <asp:ListItem>Madhubaniasp:ListItem>
            <asp:ListItem>Darbhangaasp:ListItem>
            <asp:ListItem>New Delhiasp:ListItem>
        asp:DropDownList>
        <asp:Label ID="Label2" runat="server">asp:Label>

Code File

protected void DropDownList4_SelectedIndexChanged(object sender, EventArgs e)
    {
        Label2.Text = "You have selected " + DropDownList4.SelectedItem.Text;
    }

0 comments:

Post a Comment