【发布时间】:2019-03-27 17:27:52
【问题描述】:
我已经尝试了多种方法让我的程序通过使用 try get 来捕获错误,当用户没有在其中一个文本框的文本框中输入任何数据时,当用户没有准确输入 9 时数字到文本块。我正在使用 C# WPF。
我尝试了很多不同的方法。一个似乎有效的方法是当我转换为整数时,它似乎由于某种原因捕获了它,但我使用的是字符串。例如
try
{
// remmeber, textboxes always capture the data as a string therefore we need to convert to an integer
CourseDetails.Name = Convert.ToInt32(txtName.Text);
CourseDetails.SCNnumber = Convert.ToInt32(txtSCNnumber.Text);
}
// if something does go wrong with any of the instructions in the try block then we will catch the error rather than crash the program
catch (Exception)
{
MessageBox.Show("Please complete all fields");
return;
}
try
{
if (txtName.Text.Length < 0)
{
MessageBox.Show("Enter your full name");
}
else
{
CourseDetails.Name = txtName.Text;
}
if (txtSCNnumber.Text.Length != 9)
{
MessageBox.Show("SCN number must be 9 characters long");
}
else
{
CourseDetails.SCNnumber = txtSCNnumber.Text;
}
}
catch (Exception)
{
MessageBox.Show("Please complete all fields");
}
我正在寻找的结果是,当用户在第一个文本框中输入数据时,应将其保存到变量 CourseDetails.Name 中,否则如果将其留空,程序会将其视为错误并显示信息。
对于第二个文本框,如果用户输入的不是 9 个字符,那么程序将显示一条错误消息,指出电话号码必须超过 9 个字符。否则程序会将用户输入保存到变量CourseDetails.SCNnumber
【问题讨论】:
-
注意:您可能需要考虑
string.IsNullOrWhitespace(txtName.Text)来检查是否输入了名称。不允许只输入空格。