Sunday, August 26, 2012

Using a Dropdown with Yes No instead of 1 or 0 in a GridView

Showing Yes or No instead of 1 or 0 in GridView
So you have a table that you are using and instead of storing "Yes," or "No," you're using 1 to signify yes, and a 0 to signify no.  When you display the data in your ASP.NET gridview, you want it to show YES in the column or NO.  In addition, when entering edit mode you want the user to be able to select YES or NO from the dropdown instead of using 1 or 0.

You don't have to have another sqldatasource to bind a yes or a no.  Try this solution and let me know if this works for you.

<asp:TemplateField HeaderText="YOUR_FIELD" SortExpression="YOUR_FIELD">
    <EditItemTemplate>
        <asp:DropDownList ID="dropYesNo" runat="server" SelectedValue='<%# Bind("YOUR_FIELD") %>' >
            <asp:ListItem Value="0">No</asp:ListItem>
            <asp:ListItem Value="1">Yes</asp:ListItem>
        </asp:DropDownList>
    </EditItemTemplate>
    <ItemTemplate>
        <%#Eval("YOUR_FIELD").ToString() == "1" ? "Yes" : "No" %>
    </ItemTemplate>
    <HeaderStyle HorizontalAlign="Center" />
    <ItemStyle HorizontalAlign="Center" />
</asp:TemplateField>


Of course, the field that you want needs to be converted to a TEMPLATE FIELD.  Let me know if you don't know how to do that and I'll help or post how to.

Yes or No binds from DropDown
Notice the text YOUR_FIELD, that is what you call your 0,1 value field meaning what you want to display as Yes or No in the gridview.  In my case it was "Show."  Whether I want the item to show on my website live or no. Replace this with the name of your field that you are using.

I use
 <%#Eval("YOUR_FIELD").ToString() == "1" ? "Yes" : "No" %> 
 the EVAL to test if the field is 1 or 0 to show Yes or No in the gridview.  I put this in the ItemTemplate.

Also notice,

<asp:ListItem Value="0">No</asp:ListItem>
<asp:ListItem Value="1">Yes</asp:ListItem>

So that your 0 and 1 are written back to your table when you click update.

Happy Coding... :)