我有以下包含输入单选按钮的ListView:
<asp:ListView ID="ListView1" runat="server" DataSourceID="SqlDataSource_BGlist">
<ItemTemplate>
<input id="Radio1" name="BG_name" type="radio" value="<%# Eval("BG_fileName") % >"/>
<asp:Label ID="BG_fileNameLabel" runat="server" Text='<%# Eval("BG_fileName") %>' />
</ItemTemplate>
</asp:ListView>
<asp:SqlDataSource ID="SqlDataSource_BGlist" runat="server" ConnectionString="Data Source=tcp:cg26trmnla.database.windows.net,1433;Initial Catalog=cookniche;Integrated Security=False;User ID=PublicSQLcookniche@cg26trmnla;Password=Abounakhle80+;Connect Timeout=30;Encrypt=True" ProviderName="System.Data.SqlClient" SelectCommand="SELECT [BG_fileName] FROM [BackgroundImages]"></asp:SqlDataSource>
我想检查从后面的代码检查哪个单选按钮。我使用以下代码,但显然不正确。
foreach (ListViewItem itemRow in this.ListView1.Items)
{
RadioButton radioBtn = new RadioButton();
radioBtn = (RadioButton)itemRow.FindControl("Radio1");
if (radioBtn.Checked)
{
//do stuff
}
}
答案 0 :(得分:1)
你做得差不多。您的代码中只需要更改一些小问题。
在单选按钮中添加runat="Server"
。因为如果它不会runat="server"
那么你就不会在后面的代码中找到radiobutton。看看下面的HTML代码:
<asp:ListView ID="ListView1" runat="server" DataSourceID="SqlDataSource_BGlist">
<ItemTemplate>
<input id="Radio1" runat="server" name="BG_name" type="radio" value="<%# Eval("BG_fileName") %>"/>
<asp:Label ID="BG_fileNameLabel" runat="server" Text='<%# Eval("BG_fileName") %>' />
</ItemTemplate>
</asp:ListView>
在您的代码中,您正在转向RadioButton
此RadioButton表示服务器端控制单选按钮。而不是你应该使用HtmlInputRadioButton
,如下所示:
foreach (ListViewItem itemRow in this.ListView1.Items)
{
var radioBtn = (HtmlInputRadioButton)itemRow.FindControl("Radio1");
if (radioBtn.Checked)
{
// Do Stuff
}
}
使用RadioButton应用分组
<asp:ListView ID="ListView1" runat="server">
<ItemTemplate>
<input runat="server" name="BG_name" type="radio" ID="radio1" value='<%# Eval("Id") %>' ClientIDMode="Static" class="radioBGName" />
<asp:Label ID="BG_fileNameLabel" runat="server" Text='<%# Eval("Title") %>' />
</ItemTemplate>
</asp:ListView>
<script type="text/javascript">
$('.radioBGName').click(function () {
var controlId = $(this).attr('name');
$('.radioBGName').each(function () {
if (controlId != $(this).attr('name')) {
$(this).removeAttr('checked');
}
});
});
</script>
答案 1 :(得分:0)
protected void ListView1_ItemDataBound(object sender, ListViewItemEventArgs e)
{
if (e.Item.ItemType == ListViewItemType.DataItem)
{
RadioButton c1 = (RadioButton)e.Item.FindControl("Radio1");
if (radioBtn.Checked)
{
//do stuff
}
}
}
<强>更新强>
在Page_Load
中你需要知道行索引并像这样检索控件
RadioButton radio= this.ListView1.Items[<row_index>].FindControl("Radio1") as RadioButton