【问题标题】:Radio buttons not working when binded with DataList control与 DataList 控件绑定时,单选按钮不起作用
【发布时间】:2011-03-20 01:05:17
【问题描述】:
当我尝试在数据列表中绑定单选按钮时,它变为多选,因为它的名称属性变得不同,即使我使用 GroupName 相同。
我怎样才能让它只充当单选按钮。
<asp:DataList ID="dlRoomNo" runat="server" RepeatColumns="4">
<ItemTemplate>
<div class="orboxfour">
<ul class="boxfour">
<li>
<asp:RadioButton ID="rdoRoomNo" GroupName="roomNo"
Text='<%#Eval("Room No")%>' runat="server" />
</li>
</ul>
</div>
</ItemTemplate>
</asp:DataList>
【问题讨论】:
标签:
c#
javascript
asp.net
【解决方案1】:
this question 的回答中有很多建议。
我已经用一点 jQuery 解决了这个问题,虽然我这样做的方式可能不是最好的方式!
在我的标记中,我有一个带有
的脚本块
function SetUniqueRadioButton(current)
{
$('input:radio').attr('checked', false);
current.checked = true;
}
然后将脚本附加到 ItemDataBound 事件中我的代码隐藏中的单选按钮
String uniqueRadioButtonScript;
RadioButton radioButton;
uniqueRadioButtonScript = "javascript:SetUniqueRadioButton(this);";
if (e.Row.RowType == DataControlRowType.DataRow)
{
radioButton = (RadioButton)e.Row.FindControl("MyRadioButton");
radioButton.Attributes.Add("onclick", uniqueRadioButtonScript)
}
【解决方案2】:
最好的选择是这样的:
1.添加脚本
function fnrad(rbtn) {
var radioList = document.getElementsByTagName("input");
for (var i = 0 ; i < radioList.length; i++) {
if (radioList[i].type == "radio") {
radioList[i].name = 'a';
radioList[i].setAttribute("Checked","");
}
}
rbtn.setAttribute("Checked", "checked");
}
数据列表会是这样的:
<asp:DataList ID="dlEmails" RepeatLayout="Flow" runat="server">
<HeaderTemplate>
<table>
<tr>
<th>Select Email Address </th>
<th>Status</th>
</tr>
</HeaderTemplate>
<ItemTemplate>
<tr>
<td>
<asp:RadioButton ID="rbtnSelect" Text='<%#Eval("Emails") %>' onclick='fnrad(this);' GroupName="a" Checked='<%#Eval("Primary") %>' runat="server" /><br />
(<asp:Label ID="lblId" runat="server" Text='<%#Eval("Verified") %>'> </asp:Label>)
</td>
<td valign="middle">
<asp:Label ID="Label2" Style="display: none;" runat="server" Text='<%#Eval("Id") %>'> </asp:Label>
<asp:Label ID="Label1" runat="server" Text='<%#Eval("Main") %>'> </asp:Label>
</td>
</tr>
</ItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:DataList>