<ul class="ulGroup" runat="server" id="ulGroup">
<li>
<input type="radio" name="grouptype" id="rdGroup1" class="css-checkbox" value="Group 1" checked="checked" runat="server" />
<label for="rdGroup1" class="css-label radGroup1">Group 1</label>
</li>
<li>
<input type="radio" name="grouptype" id="rdGroup2" class="css-checkbox" value="Group 2" runat="server" />
<label for="rdGroup2" class="css-label radGroup1">Group 2</label>
</li>
<li>
<input type="radio" name="grouptype" id="rdGroup3" class="css-checkbox" value="Group 3" runat="server" />
<label for="rdGroup3" class="css-label radGroup1">Group 3</label>
</li>
<li>
<input type="radio" name="grouptype" id="rdGroup4" class="css-checkbox" value="Group 4" runat="server" />
<label for="rdGroup4" class="css-label radGroup1">Group 4</label>
</li>
</ul>
如何检索从代码隐藏中选择的li
单选按钮。
当我运行代码时,出现以下错误:
Parser Error Message: Cannot create an object of type 'System.Boolean' from its string representation 'checked' for the 'Checked' property.
using (SqlConnection sc = new SqlConnection(gloString))
{
using (SqlCommand qSave = new SqlCommand())
{
qSave.Connection = sc;
qSave.CommandType = CommandType.Text;
qSave.CommandText = @"INSERT INTO [db1].[dbo].[tbl1] (FirstName, LastName, EmailAddress, UN, UP, DietGroup) VALUES (@FirstName, @LastName, @EmailAddress, @UN, @UP, @DietGroup)";
qSave.Parameters.AddWithValue("@FirstName", txtFirst.Value);
qSave.Parameters.AddWithValue("@LastName", txtLast.Value);
qSave.Parameters.AddWithValue("@EmailAddress", txtEmail.Value);
qSave.Parameters.AddWithValue("@UN", txtUser.Value);
qSave.Parameters.AddWithValue("@UP", txtPass.Value);
qSave.Parameters.AddWithValue("@DietGroup", rdGroup1.Checked); //Instead of rdGroup1.Checked, I would like to get which of the four radio is checked
}
}
答案 0 :(得分:1)
您应该使用此标记而不是您的标记
<asp:RadioButtonList ID="ulGroup" runat="server">
<asp:ListItem Text="Group 1" Value="Group 1" Selected="True"/>
<asp:ListItem Text="Group 2" Value="Group 2" />
<asp:ListItem Text="Group 3" Value="Group 3" />
<asp:ListItem Text="Group 4" Value="Group 4" />
</asp:RadioButtonList>
并在你的代码中改变了这个
qSave.Parameters.AddWithValue("@DietGroup", rdGroup1.Checked);
到这个
qSave.Parameters.AddWithValue("@DietGroup", ulGroup.SelectedValue);
修改强>
如果您想维护自己的标记,只需将checked="checked"
更改为checked="true"
,同时添加下一个
using System.Web.UI.HtmlControls;
然后创建一个像这样的函数
public string getSelectedRadioButton()
{
string radioSelected = string.Empty;
foreach (Control control in ulGroup.Controls)
{
if (control.GetType().Name.Equals("HtmlInputRadioButton") && (control as HtmlInputRadioButton).Checked)
{
radioSelected = (control as HtmlInputRadioButton).Value; break;
}
}
return radioSelected;
}
现在您可以通过这种方式获得所选
qSave.Parameters.AddWithValue("@DietGroup", getSelectedRadioButton());