C# 尝试捕获验证空文本框
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13519036/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
try catch validation empty text box
提问by TAM
Hey so I have the following code which should throw up the errors if the text boxes are empty but it doesn't it just carries on with what it would do were they not and adds an item with 0 or whatever to the list instead, is there a problem with my code?
嘿,所以我有下面的代码,如果文本框为空,它应该抛出错误,但它不只是继续它会做的事情,如果它们不是,而是将一个带有 0 或任何内容的项目添加到列表中,是我的代码有问题吗?
private void BtnAdd_Click(object sender, EventArgs e)
{
try
{
theVisit.name = txtName.Text;
theVisit.address = txtAddress.Text;
theVisit.arrival = DateTime.Parse(txtArrival.Text);
//Update theVisit object to reflect any changes made by the user
this.Hide();
//Hide the form
}
catch (Exception)
{
if (txtName.Text == "")
MessageBox.Show("please enter a customer name");
if(txtAddress.Text == "")
MessageBox.Show("Please enter a customer address");
if(txtArrival.Text == "")
MessageBox.Show("Please enter an arrival time");
}
NEW
新的
if (txtName.Text == "" || txtAddress.Text == "" || txtArrival.Text == "")
MessageBox.Show(" Please enter a value into all boxes");
else
theVisit.name = txtName.Text;
theVisit.address = txtAddress.Text;
theVisit.arrival = DateTime.Parse(txtArrival.Text);
//Update theVisit object to reflect any changes made by the user
采纳答案by Olivier Jacot-Descombes
The try-catch-statement is used to catch and handle exceptions. An exception can be thrown, if an index is out of bounds, if members of a variable set to null are accessed, and in many other situations. A TextBoxbeing empty is not an error by itself and does not throw an exception.
try-catch-statement 用于捕获和处理异常。如果索引超出范围,如果访问了设置为 null 的变量的成员,以及在许多其他情况下,可能会引发异常。一个TextBox是空的是不是一个错误本身并不会抛出异常。
I suggest you to use a completely different approach. Add an ErrorProviderto your form. You find it in the toolbox in the section "Components". Now you can add the following code to your form:
我建议您使用完全不同的方法。添加ErrorProvider到您的表单。您可以在“组件”部分的工具箱中找到它。现在您可以将以下代码添加到表单中:
private HashSet<Control> errorControls = new HashSet<Control>();
private void ValidateTextBox(object sender, EventArgs e)
{
var textBox = sender as TextBox;
if (textBox.Text == "") {
errorProvider1.SetError(textBox, (string)textBox.Tag);
errorControls.Add(textBox);
} else {
errorProvider1.SetError(textBox, null);
errorControls.Remove(textBox);
}
btnAdd.Enabled = errorControls.Count == 0;
}
private void Form1_Load(object sender, EventArgs e)
{
txtName.Tag = "Please enter a customer name";
txtAddress.Tag = "Please enter a customer address";
errorProvider1.BlinkStyle = ErrorBlinkStyle.NeverBlink;
ValidateTextBox(txtName, EventArgs.Empty);
ValidateTextBox(txtAddress, EventArgs.Empty);
}
Select the ValidateTextBoxmethod as error handler for the TextChangedevent of all your textboxes. Insert the desired message in the Tagproperty of the textboxes. Set the BlinkStyleproperty of the ErrorProviderto ErrorBlinkStyle.NeverBlink. You can do these settings in code or in the form designer.
选择该ValidateTextBox方法作为TextChanged所有文本框事件的错误处理程序。Tag在文本框的属性中插入所需的消息。将 的BlinkStyle属性设置ErrorProvider为ErrorBlinkStyle.NeverBlink。您可以在代码或表单设计器中进行这些设置。
Now a red error symbol will appear next to empty textboxes. If you hoover the mouse over them, a tooltip with the error message will appear.
现在,空文本框旁边会出现一个红色错误符号。如果将鼠标悬停在它们上方,则会出现带有错误消息的工具提示。
UPDATE
更新
I updated the code above to automatically disable or enable the "Add"-button. Therefore I added a HashSetthat contains all the controls currently being in an error state. If the set is empty the button is enabled, otherwise disabled.
我更新了上面的代码以自动禁用或启用“添加”按钮。因此,我添加了一个HashSet包含当前处于错误状态的所有控件。如果集合为空,则启用按钮,否则禁用。
回答by Pierluc SS
You should always be avoiding try catch where possible, because of performance hits see example below:
您应该始终尽可能避免 try catch,因为性能会受到影响,请参见下面的示例:
//set name
if(string.IsNullOrEmpty(txtName.Text)) MessageBox.Show("please enter a customer name");
else theVisit.name = txtName.Text;
//set address
if(string.IsNullOrEmpty(txtAddress.Text)) MessageBox.Show("please enter a customer address");
else theVisit.address = txtAddress.Text;
//set arrival time
if(string.IsNullOrEmpty(txtArrival.Text)) MessageBox.Show("please enter an arrival time");
else {
DateTime dt = default(DateTime);
bool successParse = DateTime.TryParse(txtArrival.Text, out dt);
if(!successParse) MessageBox.Show("please enter a valid arrival time");
else theVisit.arrival = dt;
}

