gpt4 book ai didi

c# - C#-验证时突出显示错误的控件

转载 作者:行者123 更新时间:2023-12-03 07:44:45 27 4
gpt4 key购买 nike

我试图用try catch验证Windows窗体,到目前为止,我成功了。我的目标是,当有人忘记填补空白或输入错误时,使用警告提示捕获返回消息框。现在,我还要验证的每个控件上都有Validating事件,因此当有人将其保留为空或格式不正确时,它将在控件旁边显示错误。到目前为止,这似乎还可以(至少对我而言),但是我的问题是,如果用户甚至没有单击一个框,它只会显示消息框,但不会突出显示错误的控件。

下面是我的代码:

private void createButton_Click(object sender, EventArgs e)
{
try
{
Book newBook = new Book(titleBox.Text, authBox.Text, Convert.ToInt32(yearBox.Text), Convert.ToInt32(editBox.Text), pubComboBox.Text, descBox.Text);
bookList.Add(newBook);
booklistListBox.DataSource = bookList;
}
catch (FormatException)
{
MessageBox.Show("You probably missed a gap or put in incorrect form");
}

}

以及那些验证事件:
 private void titleBox_Validating(object sender, CancelEventArgs e)
{
if (titleBox.Text.Trim() == String.Empty)
{
errorProvider.SetError(titleBox, "Title is required");
e.Cancel = true;
}
else
{
errorProvider.SetError(titleBox, "");
}
}

private void authBox_Validating(object sender, CancelEventArgs e)
{
if (authBox.Text.Trim() == String.Empty)
{
errorProvider.SetError(authBox, "Author is required");
e.Cancel = true;
}
else
{
errorProvider.SetError(authBox, "");
}
}

private void yearBox_Validating(object sender, CancelEventArgs e)
{
if (yearBox.Text.Trim() == String.Empty)
{
errorProvider.SetError(yearBox, "Year is required");
e.Cancel = true;
}
else
{
errorProvider.SetError(yearBox, "");
}
}

private void editBox_Validating(object sender, CancelEventArgs e)
{
if (editBox.Text.Trim() == String.Empty)
{
errorProvider.SetError(editBox, "Edition is required");
e.Cancel = true;
}
else
{
errorProvider.SetError(editBox, "");
}
}

private void pubComboBox_Validating(object sender, CancelEventArgs e)
{
if (pubComboBox.Text.Trim() == String.Empty)
{
errorProvider.SetError(pubComboBox, "Publisher is required");
e.Cancel = true;
}
else
{
errorProvider.SetError(pubComboBox, "");
}
}

private void descBox_Validating(object sender, CancelEventArgs e)
{
if (descBox.Text.Trim() == String.Empty)
{
errorProvider.SetError(descBox, "Description is required");
e.Cancel = true;
}
else
{
errorProvider.SetError(descBox, "");
}
}

那么,我不知道有什么方法可以通过按“创建”按钮来强制更改焦点或类似内容吗?
谢谢

最佳答案

尝试使用ValidateChildren():

private void createButton_Click(object sender, EventArgs e)
{
bool gotIssues = this.ValidateChildren();
if (gotIssues)
{
// someone didn't validate well...
}
}

关于c# - C#-验证时突出显示错误的控件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20079087/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com