Bind Data in Dropdown List control in ASP.NET using SQLDataSource

Introduction

In this blog, I explained how to bind data to Dropdown List control using SQLDataSource in web application in Asp.net

Dropdownlist Control

It’s enables users to select from a single-selection drop-down list. The drop-down list contains "n" number of items.

The DropDown List control also supports data binding, such as data to bind the control to a data source like object data source, xml data source and Sql data source, that contains the items to display in the control. This DropDown List control can be used to add data manually or even dynamically data binding from database.

DataBind Method

The method to bind the data source to the DropDown List control

DataTextField, DataValueField Property

To specify which field in the data source to bind to the Text and Value properties of each list item in the control.

SelectedIndex Property

The SelectedIndex property to programmatically determine the index of the item selected by the user from the DropDown List control.

Code

  1. <%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Dropdownlist.aspx.cs" Inherits="Dropdownlist" %>  
  2. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
  3. <html xmlns="http://www.w3.org/1999/xhtml" >  
  4. <head id="Head1" runat="server">  
  5.     <title>Asp.Net Dropdownlist control</title>  
  6. </head>  
  7. <body>  
  8.     <form id="form1" runat="server">  
  9.     <div>      
  10.     <table>  
  11.     <tr>  
  12.     <td style="height: 45px"><asp:Label ID="Label1" runat="server" Style="left: -1px; position: relative; top: 0px"  
  13.             Text="Name:" Width="46px"></asp:Label></td>  
  14.      <td style="height: 45px"><asp:DropDownList ID="DropDownList1" runat="server" DataSourceID="SqlDataSource1"  
  15.             DataTextField="EmpName" DataValueField="EmpName" Height="26px" Style="left: 3px;  
  16.             position: relative; top: 0px" Width="125px">  
  17.          <asp:ListItem> << Select >></asp:ListItem>  
  18.         </asp:DropDownList></td>  
  19.      <td style="height: 45px">  
  20.         <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:masterConnectionString %>"  
  21.             SelectCommand="SELECT [EmpName] FROM [tbl_employee_profile]"></asp:SqlDataSource></td>  
  22.     </tr>  
  23.     </table>  
  24.         <asp:DropDownList ID="DropDownList" runat="server">  
  25.         </asp:DropDownList>  
  26.     </div>  
  27.     </form>  
  28. </body>  
  29. </html>