如何在C#中检查输入是字符串还是字节?

时间:2016-08-26 11:51:46

标签: c# .net winforms c#-6.0

我做了一个非常简单的程序,用户需要写下他的名字和年龄。然后会弹出一个消息框,显示名称和年龄。 (http://imgur.com/a/Kqb1r

public partial class MySecondApplication : Form
{
    public MySecondApplication()
    {
        InitializeComponent();
    }

    private void txtName_TextChanged(object sender, EventArgs e)
    {
        txtAge.Enabled = true;
    }

    private void txtAge_TextChanged(object sender, EventArgs e)
    {
        cmdSubmit.Enabled = true;
    }

    private void cmdSubmit_Click(object sender, EventArgs e)
    {
        var name = txtName.Text;
        var age = Convert.ToByte(txtAge.Text);
        MessageBox.Show($"Your name is {name} and You're {age} years old.");
    }

    private void cmdExit_Click(object sender, EventArgs e)
    {
        Close();
    }
}

如何执行此操作:如果age是一个字符串,则会弹出一个消息框并说“"年龄不是数字,用户需要再次尝试"?

4 个答案:

答案 0 :(得分:2)

var name = txtName.Text;
Byte outAge;
bool result= Byte.TryParse(txtAge.Text, NumberStyles.Integer,null as IFormatProvider, out outAge);

if (!result)
{
//show your message box;
}
else
{
var age=outAge;
}

请查看以下链接以获取简要说明

https://msdn.microsoft.com/en-us/library/tkktxbeh(v=vs.110).aspx

答案 1 :(得分:1)

试试这个:

private void cmdSubmit_Click(object sender, EventArgs e)
{
    var name = txtName.Text;
    int age;
    if(Int32.TryParse("txtAge.Text, out age))
    {
        MessageBox.Show($"Your name is {name} and You're {age} years old.");
    }
    else
    {
        MessageBox.Show("Enter valid age");         
    }

}

答案 2 :(得分:1)

尝试使用NumericUpDown控件将最小值和最大值设置为某些合理值,并且不重新实现验证和解析

答案 3 :(得分:1)

从技术上讲,转换没有任何问题,如果所有数据都有效,这将有效。

    private void cmdSubmit_Click(object sender, EventArgs e)
    {
      var name = txtName.Text;
      var age = Convert.ToByte(txtAge.Text);
      MessageBox.Show($"Your name is {name} and You're {age} years old.");
    }

有多种方法可以验证您的数据,这是您可能想要使用的另一种方法。

    private void cmdSubmit_Click(object sender, EventArgs e)
    {
      string name = txtName.Text;
      short age; //This is an Int16 with a range of -32,768 to +32,767
      short.TryParse(txtAge.Text,out age);
      string ageStatement = age == 0 ? "your age is unknown" : 
                                      $"you're {age} years old";
      MessageBox.Show($"Your name is {name} and {ageStatement}.");

TryParse

    short.TryParse(txtAge.Text,out age);

如果txtAge.Text中的字符串数据不是数字,则TryParse会将age(out参数)设置为0(零)