Filling a Drop-down List with Data from a SqlDataSource

Filling a Drop-down List with Data from a SqlDataSource

To fill a drop-down list with data from a SqlDataSource in ASP.NET, you can use the DataSource property of the DropDownList control. Here are the steps:

Define a SqlDataSource control in your markup that selects the data you want to display in the drop-down list. For example:

<asp:SqlDataSource ID=”SqlDataSource1″ runat=”server” ConnectionString=”<%$ ConnectionStrings:NorthwindConnectionString %>”

     SelectCommand=”SELECT DISTINCT Country FROM Customers ORDER BY Country”></asp:SqlDataSource>

Add a DropDownList control to your markup and set its DataSourceID property to the ID of the SqlDataSource control. For example:

<asp:DropDownList ID=”DropDownList1″ runat=”server” DataSourceID=”SqlDataSource1″></asp:DropDownList>

Optionally, you can set the DataTextField and DataValueField properties of the DropDownList control to the names of the columns you want to display and use as the value of the items in the drop-down list, respectively. For example:

<asp:DropDownList ID=”DropDownList1″ runat=”server” DataSourceID=”SqlDataSource1″ DataTextField=”Country” DataValueField=”Country”></asp:DropDownList>

Run your application to see the populated drop-down list.

When the page loads, the SqlDataSource control retrieves the data from the database and fills the DropDownList control. The DataTextField and DataValueField properties of the DropDownList control specify which columns to display and use as the value of the items in the drop-down list, respectively.

Apply for ASP.NET Certification Now!!

https://www.vskills.in/certification/certified-aspnet-programmer

Back to Tutorial

Get industry recognized certification – Contact us

Menu