Thursday, March 3, 2011

Databound DropDownLists

So you want to populate a DropDownList with values from a database, huh? Well, it is not incredibly hard. You can do it from the designer by hovering over the DropDownList and selecting "Choose Data Source..." from the smart tag. You can also do it from code like so:


  1.         <asp:DropDownList ID="DropDownList1" runat="server"
  2.            DataSourceID="SqlDataSource12" DataTextField="linkShortDesc"
  3.            DataValueField="linkShortDesc">
  4.         </asp:DropDownList>
  5.         <asp:SqlDataSource ID="SqlDataSource12" runat="server"
  6.            ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
  7.             SelectCommand="SELECT [linkShortDesc] FROM [Links]"></asp:SqlDataSource>

As you can see from the code, we created a new ASP.NET SqlDataSource, provided our connection string and our query we wanted to run. In my case I'm returning a list of links from a table. Now, in our ASP.NET DropDownList code, we can specify a DataValueField and a DataSourceID. The DataSourceID is the ID of the data source we want to link to, and DataValueField is the name of the column we want to display in our drop down list.

Happy coding!

No comments:

Post a Comment

I Break Code Where code gets done.
ASP.NET | HTML | SQL Server | VB.NET | Request A Topic |