Asp.net
檢查程式碼後面的單選按鈕時出現問題
我有一個簡單的 ASP.NET 表單,其中包含一個 DropDownList 和兩個 RadioButtons(它們都共享相同的 GroupName)。
在 DropDownList 的 SelectedIndexChanged 事件中,我設置
Checked=true了兩個 RadioButton。它設置第二個 RadioButton 很好,但它不會檢查第一個。我究竟做錯了什麼?
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication3._Default" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <body> <form id="form1" runat="server"> <asp:DropDownList runat="server" AutoPostBack="true" OnSelectedIndexChanged="ddl_Changed" ID="ddl"> <asp:ListItem Text="Foo" /> <asp:ListItem Text="Bar" /> </asp:DropDownList> <asp:RadioButton runat="server" ID="rb1" Text="Foo" GroupName="foobar" /> <asp:RadioButton runat="server" ID="rb2" Text="Bar" GroupName="foobar" /> </form> </body> </html> protected void ddl_Changed(object sender, EventArgs e) { if (ddl.SelectedIndex == 0) rb1.Checked = true; // <- Doesn't actually work else rb2.Checked = true; }
它失敗了,因為它試圖將它們都設置為選中,這對於組中的單選按鈕是不可能的。
最好的解決方案是使用 RadioButtonList:
<asp:RadioButtonList ID="rblTest" runat="server"> <asp:ListItem Text="Foo"></asp:ListItem> <asp:ListItem Text="Bar"></asp:ListItem> </asp:RadioButtonList>然後像這樣設置選定的項目:
protected void ddl_Changed(object sender, EventArgs e) { rblTest.ClearSelection(); rblTest.SelectedIndex = ddl.SelectedIndex; }
不確定這是否是正確的方法,但它有效
protected void ddl_Changed(object sender, EventArgs e) { if (ddl.SelectedIndex == 0) { rb1.Checked = true; rb2.Checked = false; } else { rb1.Checked = false; rb2.Checked = true; } }