2

我试图将单选按钮的值转换为“out”时的变量,然后将其作为真或假传递。

但它总是返回 false 我尝试了许多不同的方法,这就是我所在的位置。

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;
    }
}

当我选择“是”时它总是错误的?

4

4 回答 4

1

您的代码没有任何意义 - 它执行大量冗余分配。此外,Boolean.TryParse 无法将“YES”和“NO”解析为trueand false。它只是没有这样做,因为文档中的示例清楚地表明了这一点。它只会解析对应于Boolean.TrueStringBoolean.FalseString的字符串

它可以大大简化如下:

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!");
}
于 2013-01-04T08:49:14.587 回答
1

如果你只想有两个值,应该有'true'和'false',就足够了。如果您有更多值或更多类型,则可以使用 byte 或 int ...的类型。您应该使用 if ... else ... 或 switch ... case ...

 <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"
    }
于 2014-02-24T07:48:48.430 回答
0
<asp:RadioButtonList ID="rblTest"  runat="server" RepeatDirection="Horizontal"  >
                <asp:ListItem Value="0">
                    No
                </asp:ListItem>
                <asp:ListItem Value="1">
                    Yes
                </asp:ListItem>
</asp:RadioButtonList>

然后您可以使用您的代码 bool.TryParse 并使用 SelectedItem.Text 检查您的项目

于 2013-01-04T08:49:24.647 回答
0

您无法解析"YES"true或解析"NO"falseHabib 指出您必须使用

True,truefor booleantrue 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;
            }
        }
于 2013-01-04T08:58:42.743 回答