在tabpage中验证文本框

时间:2015-05-19 11:26:11

标签: c#

以下是我的情况:我有TabControlTabPagetabPage1& tabPage2& {{1}在每个页面中我都有8 - 10 tabPage3。我如何为textbox - Windows窗体应用程序中的验证? enter image description here

这是我的表单应用

1 个答案:

答案 0 :(得分:1)

您可以将Control Validating个活动与ErrorProvider一起使用。

我已经创建了一个示例应用程序。

它有一个2页的标签控件:

  • TabPage1
    • TextBox2中
    • textbox3
    • textbox4
    • textbox5
    • combobox1
    • combobox2
    • combobox3
    • datetimepicker1
  • TabPage2
    • TextBox1中

enter image description here

从工具箱中将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");
}

它会针对每个控件显示错误(请参阅下面的快照),并且不会提交表单。 enter image description here