在 ASP.NET 中實現 RadioButton 單選互斥,只需為同組控件設置相同的 GroupName 屬性值即可。這比傳統 HTML 的 name 屬性更靈活,支援跨命名容器、Repeater/GridView 模板列等複雜場景。
<asp:RadioButton ID="radOption1" runat="server" Text="選項一" GroupName="GroupA" />
<asp:RadioButton ID="radOption2" runat="server" Text="選項二" GroupName="GroupA" />
<asp:RadioButton ID="radOption3" runat="server" Text="選項三" GroupName="GroupA" />
在 Repeater、GridView、ListView 等模板中,為每行生成獨立分組:
<asp:Repeater ID="rptTemplates" runat="server">
<ItemTemplate>
<asp:RadioButton
ID="radTemplate"
runat="server"
Text='<%# Eval("Template_Name") %>'
GroupName='<%# "Group_" + Eval("ID") %>'
ToolTip='<%# Eval("ID") %>' />
</ItemTemplate>
</asp:Repeater>
"Group_" + Eval("ID") 確保每行數據的單選框互斥,不同行互不影響input[type=radio],瀏覽器原生實現互斥// 遍歷 Repeater 項查找選中項
foreach (RepeaterItem item in rptTemplates.Items)
{
var rb = item.FindControl("radTemplate") as RadioButton;
if (rb?.Checked == true)
{
int templateId = int.Parse(rb.ToolTip);
// 處理業務邏輯
break;
}
}
| 問題 | 原因 | 解決 |
|---|---|---|
| 分組不生效,可多選 | GroupName 拼寫不一致或為空 | 統一使用常量/變量定義組名,避免手寫拼寫錯誤 |
| 跨 UpdatePanel 分組失效 | 部分更新導致 name 屬性衝突 | 確保同組 RadioButton 在同一 UpdatePanel 內,或使用 JS 手動互斥 |
| GridView 分頁後分組重置 | 每頁重新綁定生成相同 GroupName | GroupName 包含頁碼或唯一鍵:GroupName='<%# "G_" + Container.DataItemIndex %>' |
GroupName 是 ASP.NET RadioButton 分組的核心屬性,靈活運用動態綁定可滿足各類列表單選需求。記住:同組同名,異組異名,配合命名容器隔離,即可輕鬆實現複雜單選交互。