Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 测试填充的文本框和正确的数据类型_C#_Textbox_Try Catch - Fatal编程技术网

C# 测试填充的文本框和正确的数据类型

C# 测试填充的文本框和正确的数据类型,c#,textbox,try-catch,C#,Textbox,Try Catch,我在C#,Windows窗体应用程序中工作 我有6个接受用户输入的文本框。单击“提交”按钮时,它将值存储在数组中。我想创建一些东西来检查文本框中的两件事1.)文本框中有一些东西,2.)信息只是一个数字,其他什么都没有 我被告知一个try-catch循环可以做到这一点,但我还没有弄清楚如何做到 谢谢你能提供的任何帮助 // In button_click event or somewhere like that if (!this.CheckInput(txt_TextBox1)) re

我在C#,Windows窗体应用程序中工作

我有6个接受用户输入的文本框。单击“提交”按钮时,它将值存储在数组中。我想创建一些东西来检查文本框中的两件事1.)文本框中有一些东西,2.)信息只是一个数字,其他什么都没有

我被告知一个try-catch循环可以做到这一点,但我还没有弄清楚如何做到

谢谢你能提供的任何帮助

// In button_click event or somewhere like that

if (!this.CheckInput(txt_TextBox1))
    return;

if (!this.CheckInput(txt_TextBox2))
    return;

if (!this.CheckInput(txt_TextBox3))
    return;

// Everything OK, do something
然后像这样的方法:

private bool CheckInput(TextBox textbox) {

    int test;

    if (!int.TryParse(textbox.Text.Trim(), out test)) {
        MessageBox.Show("Invalid input");
        return false;
    }

    return true;
}
然后像这样的方法:

private bool CheckInput(TextBox textbox) {

    int test;

    if (!int.TryParse(textbox.Text.Trim(), out test)) {
        MessageBox.Show("Invalid input");
        return false;
    }

    return true;
}

要检查文本框中是否有内容,可以调用string.IsNullOrEmpty方法


<>当检查文本框是否包含数值时,您可能需要考虑。这将是一种比在输入值后阻止它更为用户友好的方法。

要检查文本框中是否有内容,可以调用string.IsNullOrEmpty方法


<>当检查文本框是否包含数值时,您可能需要考虑。这将是一种比在输入值后阻止更为用户友好的方法。

您不想为此使用try-catch块-您不应该对标准应用程序流使用异常,因为这是一个相对昂贵的选项

检查它是否为空

string.IsNullOrEmpty(textbox1.Text);
检查它是否是一个数字

int result;
int.TryParse(textbox1.Text), out result);

您不想为此使用try-catch块-不应该对标准应用程序流使用异常,因为这是一个相对昂贵的选项

检查它是否为空

string.IsNullOrEmpty(textbox1.Text);
检查它是否是一个数字

int result;
int.TryParse(textbox1.Text), out result);

您可以按照上面的Bas建议使用isNullOrEmtpy来检查是否有任何用户输入。
对于数字,我建议您使用正则表达式。您可以找到一个解决方案

您可以按照上面Bas的建议使用isNullOrEmtpy来检查是否有任何用户输入。 对于数字,我建议您使用正则表达式。你可以找到解决办法