Databound List Boxes

This one had me stumped for a little while until I was kicked in the right direction.

The Problem

You have two tables, Address and State. Address contains an attribute StateId, which is a primary key in the State table. You create a GridView to allow users to edit the address records. But, rather than displaying the StateId, you want to display a DropdDwnList that's populated from the State table. You don't want to have to do an extraordinary amount of coding to make this work, and you don't have the resources to buy an 3rd party component.

The Solution

Version 2.0 of the .NET Framework has some nifty new data-binding options. And this I just came across today. The ASP.NET team created a Quickstart tutorial on this databinding method, so I'll paste the important parts here. What we have is a typical GridView (with only one template column). But what you should notice is that the DropDownList is bound to two different sources! The SelectedValue is bound to the corresponding row in the GridView (from SqlDataSource1) whereas the list itself is populated from SqlDataSource2.

<asp:GridView ID="GridView1" AllowSorting="True" AllowPaging="True" Runat="server"
DataSourceID="SqlDataSource1" AutoGenerateEditButton="True" DataKeyNames="au_id"
AutoGenerateColumns="False">

<Columns>
<asp:TemplateField SortExpression="state" HeaderText="state">
<EditItemTemplate>
        <asp:DropDownList ID="DropDownList2" Runat="server" DataTextField="state"
DataSourceID="SqlDataSource2" SelectedValue='<%# Bind("state") %>'
DataValueField="state" />

</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label1" Runat="server" Text='<%# Eval("state") %>' />
</ItemTemplate>
</asp:TemplateField>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" Runat="server" SelectCommand="SELECT [au_id],
[au_lname], [au_fname], [phone], [address], [city], [state], [zip], [contract]
FROM [authors] WHERE [state] = @state"
UpdateCommand="UPDATE [authors] SET [au_lname] = @au_lname, [au_fname] = @au_fname,
[phone] = @phone, [address] = @address, [city] = @city, [state] = @state,
[zip] = @zip, [contract] = @contract WHERE [au_id] = @au_id"
ConnectionString="<%$ ConnectionStrings:Pubs %>">

<SelectParameters>
<asp:ControlParameter Name="state" ControlID="DropDownList1" />
</SelectParameters>
</asp:SqlDataSource>
<asp:SqlDataSource ID="SqlDataSource2" Runat="server" SelectCommand="SELECT DISTINCT [state]
FROM [authors]"
ConnectionString="<%$ ConnectionStrings:Pubs %>" />

The full source for this sample, in both C# and VB.NET can be in the Beta QuickStart tutorials (https://beta.asp.net/quickstart/aspnet/). Click on Performing Data Access, then scroll down to the Data Binding in Templates tutorial.

I'm starting to realize there's much to learn about new changes coming down the pike with the next version of the .NET Framework. Time to get cracking!

j.