为简易EditItemTemplate添加"Yes/No"下拉列表
Hey Andy, let's get those Y/N dropdowns set up for your Priority columns—this is totally doable in ASP.NET Web Forms, even if it feels trickier than classic ASP at first! Here's exactly how to make it work:
方法1:通过设计器可视化配置(快速上手)
If you prefer point-and-click setup, this is the way to go:
- Right-click your GridView/DetailsView control and select Edit Templates.
- Navigate to the
EditItemTemplatefor one of your Priority columns (like Priority1). - Delete the default TextBox that's there, then drag a
DropDownListcontrol into the template. - Open the DropDownList's properties panel, find the Items collection, and add two ListItems:
- One with Text = "Yes" and Value = "Y"
- Another with Text = "No" and Value = "N"
- To make sure the dropdown shows the current value when entering edit mode, go to the DropDownList's DataBindings section, bind the
SelectedValueproperty to your corresponding field (e.g., Priority1). - Repeat these steps for Priority2 through Priority5.
- Double-check your data source control (like SqlDataSource) has an UpdateCommand that includes all Priority columns, with matching parameters.
方法2:手动编写模板代码(更灵活)
If you'd rather code the template directly in your ASPX file, here's a clean example for one column—just replicate this for the other four:
<asp:TemplateField HeaderText="Priority 1"> <!-- 显示模式下的友好文本 --> <ItemTemplate> <%# Eval("Priority1").ToString() == "Y" ? "Yes" : "No" %> </ItemTemplate> <!-- 编辑模式下的下拉列表 --> <EditItemTemplate> <asp:DropDownList ID="ddlPriority1" runat="server" SelectedValue='<%# Bind("Priority1") %>'> <asp:ListItem Text="Yes" Value="Y"></asp:ListItem> <asp:ListItem Text="No" Value="N"></asp:ListItem> </asp:DropDownList> </EditItemTemplate> </asp:TemplateField>
The Bind() method here is key—it handles both reading the current value (so the dropdown selects the right option when editing starts) and writing the selected value back to your database when you update.
关键注意事项
- Always use
Bind()instead ofEval()for the dropdown's SelectedValue—Eval()is read-only, whileBind()supports two-way data binding needed for updates. - If you're handling updates in code-behind (e.g., using the GridView's
RowUpdatingevent), you'll need to grab each dropdown's value manually:
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e) { // 获取Priority1的下拉列表控件 DropDownList ddlPriority1 = (DropDownList)GridView1.Rows[e.RowIndex].FindControl("ddlPriority1"); // 更新参数值 e.NewValues["Priority1"] = ddlPriority1.SelectedValue; // 对Priority2到Priority5重复上面的操作 DropDownList ddlPriority2 = (DropDownList)GridView1.Rows[e.RowIndex].FindControl("ddlPriority2"); e.NewValues["Priority2"] = ddlPriority2.SelectedValue; }
- Make sure your database columns are indeed
char(1)—this matches the "Y"/"N" values perfectly, so you won't run into truncation issues.
内容的提问来源于stack exchange,提问作者Andy
相关产品推荐
相关产品推荐

