Monday, November 16, 2009

DropDownList in a GridView with no code-behind / events handling needed

So, you have a GridView and you want to add a DropDownList to one of the columns. Typically, I would have populated the data and selected the proper item in the DropDownList. This code always seemed silly to me. They I saw in a Microsoft article how they did it. No code-behind or event handling needed. One note, I didn’t use the SqlDataSource and instead used the ObjectDataSource.

I could not do step 20 where they bind using the Field Binding radio button for City. I was however able to set the Custom Binding. Just typed it in there. Or you can do it from .aspx/.ascx page directly.

I did add my ObjectDataSource (you only need to worry about the select method) to the page and wired it up to the DropDownList.

Here is my ObjectDataSource

<asp:ObjectDataSource ID="dsMyDataSource" runat="server" SelectMethod="GetDropDownListItems" TypeName="DataModel.DAL" />

Let’s assume you have converted your field to a template already (if you haven’t you’ll have to). This means you have something similar to this.

<asp:TemplateField HeaderText="City">
<ItemTemplate>
<asp:Label ID="txtCity" runat="server" Text='<%# Bind("City") %>'/>
</ItemTemplate>
</asp:TemplateField>

Now you want to make that into a DropDownList of Cities. The process change is very minimal actually. Just make it look like the following:

<asp:TemplateField HeaderText="City">
<ItemTemplate>
<asp:DropDownList ID="ddlCity" runat="server" SelectedValue='<%# Bind("txtCity") %>'
DataSourceID="dsMyDataSource"
DataTextField="City"
DataValueField="City"/>
</ItemTemplate>
</asp:TemplateField>

So, you can go through all that document says, or you can make a few changes as noted here. Of course, the really crazy way now is to use code-behind. In all honesty, there is always a reason for different ways. This is a quite and powerful way to do this.

No comments: