以下是我的情况:我有TabControl
个TabPage
个tabPage1
& tabPage2
& {{1}在每个页面中我都有8 - 10 tabPage3
。我如何为textbox
- Windows窗体应用程序中的验证?
这是我的表单应用
答案 0 :(得分:1)
您可以将Control
Validating
个活动与ErrorProvider
一起使用。
我已经创建了一个示例应用程序。
它有一个2页的标签控件:
从工具箱中将ErrorProvider
控件添加到form
。
在form
的构造函数中,订阅所有控件的验证事件:
textBox1.Validating += textBox_Validating;
textBox2.Validating += textBox_Validating;
textBox3.Validating += textBox_Validating;
textBox4.Validating += textBox_Validating;
textBox5.Validating += textBox_Validating;
comboBox1.Validating += comboBox_Validating;
comboBox2.Validating += comboBox_Validating;
comboBox3.Validating += comboBox_Validating;
dateTimePicker1.Validating += dateTimePicker1_Validating;
以下是检查空值的事件:
bool IsValidated = true; //will be checked on button click
void dateTimePicker1_Validating(object sender, CancelEventArgs e)
{
DateTimePicker datetimepicker = sender as DateTimePicker;
if (datetimepicker.Value == null)
{
errorProvider1.SetError(datetimepicker, "Required");
IsValidated = false;
}
}
void comboBox_Validating(object sender, CancelEventArgs e)
{
ComboBox combo = sender as ComboBox;
if(combo.SelectedIndex == -1)
{
errorProvider1.SetError(combo, "Required");
IsValidated = false;
}
}
void textBox_Validating(object sender, CancelEventArgs e)
{
TextBox txtbox = sender as TextBox;
if (txtbox.Text == "" || txtbox.Text.Length > 2)
{
errorProvider1.SetError(txtbox, "Required");
IsValidated = false;
}
}
当您从任何控件中失去焦点时, Validating
事件会触发,但如果有人直接点击Submit
按钮会怎么样?
要解决此问题,您还可以在按钮单击时验证所有选项卡的所有控件:
private void btnSubmit_Click(object sender, EventArgs e)
{
//traverse all Tab Pages
foreach (TabPage tabpage in tabControl1.Controls.OfType<TabPage>())
{
foreach (TextBox txtbox in tabpage.Controls.OfType<TextBox>())
textBox_Validating(txtbox, null);
foreach (ComboBox combo in tabpage.Controls.OfType<ComboBox>())
comboBox_Validating(combo, null);
foreach (DateTimePicker date in tabpage.Controls.OfType<DateTimePicker>())
dateTimePicker1_Validating(date, null);
}
if (IsValidated)
MessageBox.Show("submitted");
else
MessageBox.Show("not submitted");
}
它会针对每个控件显示错误(请参阅下面的快照),并且不会提交表单。