This is my last attempt to solve the problem of my Radio button scenario. I can't figure out how to select one button only. (By the way I can't use RadioButtonList cause it doesn't allow html codes inside its block so it doesn't suit me).
I have a list of pictures and radio buttons that are selected in a ListView as follows:
<asp:ListView ID="ListView1" runat="server" DataSourceID="SqlDataSource_BGlist">
<ItemTemplate>
<input id="Radio1" name="BG_list" type="radio" runat="server" value='<%# Eval("BG_fileName") %>'/>
<img alt="" style="width:150px" src="/Images/Editors/BG/<%# Eval("BG_fileName") %>">
</ItemTemplate>
</asp:ListView>
Unfortunately the ListView mechanism assigns a different name to each radio button behind the scene which means that I can select multiple radio buttons. I want to be able to select one button only.
So I added the following script:
<script type="text/javascript">
var inputElements = document.getElementsByTagName("input");
for (var inputName in inputElements) {
var input = inputElements[inputName];
if (input.type === "radio") {
input.name = "BG_list";
}
}
Now I can select one single button BUT it created another problem in codebehind. The value of the selected button is always empty. Why? Can anyone see the error?
CODE BEHIND
foreach (ListViewItem itemRow in this.ListView1.Items)
{
//RadioButton radioBtn = (RadioButton)itemRow.FindControl("Radio1");
var radioBtn = (HtmlInputRadioButton)itemRow.FindControl("Radio1");
if (radioBtn.Checked)
{
// Do Stuff
//Response.Write(radioBtn.Value);
}
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…