输入字符串的格式不正确.处理异常



我得到异常"输入字符串的格式不正确"。我想处理那个异常并添加我自己的错误。输入应该是int。我应该在哪里做?我有一个带有listview的objectdatasource,我很难从后面的代码中获取textbox.text,所以我可以使用tryParse。

您的属性类型为Int32。您不能将除有效整数之外的任何其他值分配给此属性。现在,如果您有一些字符串形式的用户输入,然后需要将其分配给integer属性,则可以使用int.TryParse方法来确保用户输入的值是有效的整数。

例如:

string someValueEnteredByUser = ...
int value;
if (!int.TryParse(someValueEnteredByUser, out value))
{
    // the value entered by the user is not a valid integer
}
else
{
    // the value is a valid integer => you can use the value variable here
}

Number总是一个int,它是这样定义的。。。

您可能想要验证字符串的内容。最简单的方法是将其解析为int:

int number;
if(!int.TryParse(yourString, out number))
{
   Not an int!
}

'value'将始终与变量的类型相同。因此有了这个:

private bool mabool = false; 
public bool MaBool
{
    get { return mabool; }
    set { mabool = value; }
}

永远不会崩溃。这是因为,正如我所说,值将是相同类型的变量。在这种情况下,值是布尔值。

试试类

public class Rotator
{
    public Roll, Pitch, Yaw;
    // Declarations here (...)
}
private Rotator rotation = new Rotator();
public Rotator Rotation
{
    get { return rotation; }
    set
    {
        // Since value is of the same type as our variable (Rotator)
        // then we can access it's components.
        if (value.Yaw > 180) // Limit yaw to a maximum of 180°
            value.Yaw = 180;
        else if (value.Yaw < -180) // Limit yaw to a minimum of -180°
            value.Yaw = -180;
        rotation = value;
    }
}

如第二个示例所示,value是一个Rotator,因此我们可以访问它的组件。

最新更新