Skip to content

Assigning a DropDownList Value in a ASP.NET GridView Using ObjectDataSource

Updated: at 11:17 PM

As a moderator in the asp.net forums, I often see the same or similar questions.  The answer to this question is pretty straight forward but not 100% obvious so I thought I'd do a post about in the hopes that with a couple key words, people will find the answer.  The title basically says it all.  We have a GridView that has a data column of type bool.  We want to display in the GridView Yes or No depending on whether the data value is true or false.  The example I'm showing does not help with making this an editable field (maybe a theme for another post if this one is popular) but simply shows yes or no.

The solution involves first dropping a GridView and ObjectDataSource onto your design surface in Visual Studio.  Then, using the little chevron on the GridView, choose edit columns and convert the column you are interested in making a DropDownList into a template.  From there replace the ItemTemplate with the DropDownList code below.  You get the code below.

 

<%@ Page Language="C#" %>
 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 
<script runat="server">
 
</script>
 
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>ODS DDL Example</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:ObjectDataSource ID="ObjectDataSource1" runat="server" SelectMethod="GetMembers"
            TypeName="BusinessObject"></asp:ObjectDataSource>
        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="Id"
            DataSourceID="ObjectDataSource1">
            <Columns>
                <asp:BoundField DataField="Id" HeaderText="Id" ReadOnly="True" SortExpression="Id" />
                <asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name" />
                <asp:BoundField DataField="Email" HeaderText="Email" SortExpression="Email" />
                <asp:TemplateField HeaderText="Approved" SortExpression="Approved">
                    <ItemTemplate>
                        <asp:DropDownList ID="DropDownListUser" runat="server" AutoPostBack="False" 
                            SelectedValue='<%# Bind("Approved") %>'>
                            <asp:ListItem Text="Yes" Value="True"></asp:ListItem>
                            <asp:ListItem Text="No" Value="False"></asp:ListItem>
                        </asp:DropDownList>
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
        </asp:GridView>
    </div>
    </form>
</body>
</html>

 

And, when you run this code (assuming you have a simple business object that returns some data), you get this:

 

x

Hope this helps!