Skip to content

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

Updated: at 11:17 PM

As a moderator in the 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" 
<script runat="server">
<html xmlns="">
<head runat="server">
    <title>ODS DDL Example</title>
    <form id="form1" runat="server">
        <asp:ObjectDataSource ID="ObjectDataSource1" runat="server" SelectMethod="GetMembers"
        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="Id"
                <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">
                        <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>


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



Hope this helps!