Home Articles CodeDigest Tutorials FAQs
Home > CodeDigest >  

Binding DropDownList from CodeBehind and ASPX by Fetching Data From Database in ASP.Net
Submitted By Satheesh Babu B
On 10/18/2008 7:25:28 AM

Most of the times, we will have the dropdownlist items in sql server database which needs to be populated when loading the page.

In  this little code snippet, we will try to achieve this by 2 ways,

1. Binding From CodeBehind


 <asp:DropDownList ID="ddlRoles" runat="server" Width="10em">



protected void Page_Load(object sender, EventArgs e)


        if (!IsPostBack)


         ddlRoles.DataSource = GetAllRoles();

         ddlRoles.DataValueField = "RoleID";

         ddlRoles.DataTextField = "Role";


         ddlRoles.Items.Insert(0, new ListItem("Select",""));




public DataTable GetAllRoles()


        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Sql"].ConnectionString);


        SqlCommand com = new SqlCommand("SP_GetAllRoles", con);

        com.CommandType = CommandType.StoredProcedure;

        SqlDataAdapter ada = new SqlDataAdapter(com);

        DataTable dt = new DataTable();


        return dt;



In the above code, I have given the database column name "RoleID" that should be populated for value field of ListItem. Similarly, Role for text field.


2. Binding from ASPX page

We can also bind the dropdownlist from ASPX page by calling function GetAllRoles(). The only constraint is we should make the function as public to access it from ASPX page.



<asp:DropDownList ID="ddlRoles" DataSource='<%# GetAllRoles() %>'

                                DataTextField="Role"  DataValueField="RoleID"

                                SelectedValue='<%# Bind("RoleID") %>' runat="server">


Recent Codes
  • View All Codes..