没有值时发生错误

时间:2014-02-23 04:48:46

标签: c#

我创建了一个程序,要求用户在文本框中输入值。如果用户没有输入任何值,我正在尝试将文本框默认为0

目前,如果没有输入值并尝试计算,我会收到错误“输入字符串格式不正确”错误。

这就是我所拥有的:

cexp = int.Parse(currentexp.Text); currentexp.Text = "";

我想尝试做这样的事情:

if (currentexp.text == "") set cexp = 0

因此,如果文本框为空,那么我想将变量cexp设置为等于0.

3 个答案:

答案 0 :(得分:3)

解决方案1:您可以使用Conditional operator来设置默认值。

int cexp=(!String.IsNullOrWhiteSpace(currentexp.Text)) ? Convert.ToInt32(currentexp.text) : 0;

解决方案2 :您可以使用int.TryParse()执行验证。

int cexp;
if(int.TryParse(currentexp.Text,out cexp))
{
//conversion successfull do some thing here
}
else
{
//conversion failed so do something here
}

答案 1 :(得分:1)

您可以使用LINQ和条件运算符:

cexp = !currentexp.Text.All(char.IsDigit) ||
       !currentexp.Text.Any() ? 0 :  int.Parse(currentexp.Text)

cexp包含一个或多个非数字字符时,这会将currentexp.Text设置为零。

答案 2 :(得分:0)

最好使用int.TryParse,因为用户正在输入数据。

int cexp = 0;
if (!int.TryParse(textBox1.Text, out cexp))
{
    var result = MessageBox.Show("An invalid entry was entered, do you want to use 0 instead?", 
                                 "Invalid Entry", MessageBoxButtons.YesNo);
    if (result == DialogResult.Yes)
    {
        //do stuff to continue here
        //cexp will already be 0
    }
    else
    {
        //don't continue, they wanted to try again
    }
}

这会将cexp的值默认为0,如果用户输入的内容无效,则会警告它们(并且仍然将cexp保持为0)。如果他们输入正确的值,则cexp将更新为用户输入的内容。

如果您不想警告用户或任何事情,只想继续,这将有效。

int cexp = 0; //default to 0
int.TryParse(currentexptextBox1.Text, out cexp); //try to get a number, if it fails, cexp will still be 0