Static DropDownList in GridView« View all ASP.net articles
December 20, 2006
There are times when you want to limit the data entered in your GridView to preselected choices. Having a DropDownList in the edit state of your GridView can easily achieve this task.
This example uses a GridView with 2 columns from the "Article" table. The 2 columns are "Article_Title" and "Featured." We want to limit the entry choices the featured column to 1 or 0.
Our original GridView in edit mode looks like this:
Our first step is to convert the "Featured" column to a template field or as Visual Web Developer labels it: Convert this field into a TemplateField.
Edit the GridView's Columns

Convert the "Featured" column into a TemplateField.

The souce code for the Featured column is the following. We will replace the EditItemTemplate's TextBox with a DropDownList.
<asp:TemplateField HeaderText="Featured" SortExpression="Featured">
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("Featured") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("Featured") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
Our new code with the DropDownList. Notice that we simply added a DropDownList with 2 ListItems
<asp:TemplateField HeaderText="Featured" SortExpression="Featured">
<EditItemTemplate>
<asp:DropDownList ID="ddlFeatured" runat="server">
<asp:ListItem Value="1">Yes</asp:ListItem>
<asp:ListItem Value="0">No</asp:ListItem>
</asp:DropDownList>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("Featured") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
We achieved our task. The new GridView in edit mode now has a DropDownList that limits input to Yes=1 and No=0.
| |
Article_Title | Featured |
| Update Cancel |
How do you enable word wrap in Microsoft Visual Studio 2005? |
|
| Edit |
A potentially dangerous Request.Form value was detected from the client.. |
|
| Edit |
How to Replace Text in ASP.net GridView |
|
| Edit |
Remove Internet Explorer 7 and rollback to Internet Explorer 6 |
|
|