Asp.net 将单选按钮值转换为布尔值
我正在尝试将单选按钮的值转换为一个变量,然后该变量将作为true或false传递 但它总是返回错误,我已经尝试了许多不同的方法,这就是我所处的位置Asp.net 将单选按钮值转换为布尔值,asp.net,Asp.net,我正在尝试将单选按钮的值转换为一个变量,然后该变量将作为true或false传递 但它总是返回错误,我已经尝试了许多不同的方法,这就是我所处的位置 if (rad_Security_Risk.SelectedItem.Value == "NO") { if (bool.TryParse(rad_Security_Risk.SelectedValue, out risk)) { risk = false; obj.Security_Risk = ri
if (rad_Security_Risk.SelectedItem.Value == "NO")
{
if (bool.TryParse(rad_Security_Risk.SelectedValue, out risk))
{
risk = false;
obj.Security_Risk = risk;
}
}
if (rad_Security_Risk.SelectedItem.Value == "YES")
{
if (bool.TryParse(rad_Security_Risk.SelectedValue, out risk))
{
risk = true;
obj.Security_Risk = risk;
}
}
当我选择“是”时,它总是为false?您的代码没有意义,因为它执行大量冗余赋值。此外,Boolean.TryParse无法将“YES”和“NO”解析为
true
和false
。它只是没有做到这一点。它将只解析与或相对应的字符串
它可以大大简化为:
if (rad_Security_Risk.SelectedItem.Value == "NO")
{
obj.Security_Risk = false;
}
else if (rad_Security_Risk.SelectedItem.Value == "YES")
{
obj.Security_Risk = true;
}
else
{
// Is there a possibility that the value can be something
// other than YES or NO?
throw new Exception ("Undefined behaviour!");
}
不
对
然后你可以使用你的代码bool.TryParse,也可以使用SelectedItem.Text检查你的项目。你不能像Habib指出的那样,将“YES”解析为“true”或将“NO”解析为“false”
True,True
对于布尔值True
False,False
用于解析时的布尔值False
请改用此代码
if (rad_Security_Risk.SelectedItem.Value == "NO")
{
if (bool.TryParse("False", out risk))
{
risk = false;
obj.Security_Risk = risk;
}
}
if (rad_Security_Risk.SelectedItem.Value == "YES")
{
if (bool.TryParse("True", out risk))
{
risk = true;
obj.Security_Risk = risk;
}
}
如果你只想有两个值,应该有'true'和'false',就足够了。如果有更多值或更多类型,则可以使用byte或int…类型。。。。你应该使用if。。。其他的或切换。。。案例
<asp:RadioButtonList ID="rblList" runat="server">
<asp:ListItem Text="True" Value="True" Selected="True"></asp:ListItem>
<asp:ListItem Text="False" Value="False"></asp:ListItem>
</asp:RadioButtonList>
var a = Convert.ToBoolean(rblList.SelectedValue);
或
既然你在
if
,你已经知道这是真的,为什么还要将“YES”解析为bool
?因为这是我的经理希望我做的。他让我把db改了一点,想让我把它改过来!!非常感谢。当别人看到它时,它总是显得简单。我得到的指令是使用tryparse转换值。因此,除了显而易见的方式外,最终有很多不同的方式。
<asp:RadioButtonList ID="rblList" runat="server">
<asp:ListItem Text="True" Value="True" Selected="True"></asp:ListItem>
<asp:ListItem Text="False" Value="False"></asp:ListItem>
</asp:RadioButtonList>
var a = Convert.ToBoolean(rblList.SelectedValue);
var a = Convert.ToInt16(rblList.SelectedValue);
var retValue = string.Empty;
switch (a)
{
case 0:
//"you want have"
break;
case 1:
//"you want have"
break;
case 2:
//"you want have"
break;
default:
//"you want have"
break;
}
if (a == 0)
{
//"you want have"
}
else if (a == 1)
{
//"you want have"
}
else if (a == 2)
{
//"you want have"
}
else
{
//"you want have"
}