這裏是我的情況:我有一個TabControl
三個TabPage
的(tabPage1
& tabPage2
& tabPage3
)。在每一頁我有一個8 - 10 textbox
。我如何爲textbox, combobox, datetimepicker
- 在Windows窗體應用程序中進行驗證? 驗證的文本框的標籤頁
這是我的表單應用程序
這裏是我的情況:我有一個TabControl
三個TabPage
的(tabPage1
& tabPage2
& tabPage3
)。在每一頁我有一個8 - 10 textbox
。我如何爲textbox, combobox, datetimepicker
- 在Windows窗體應用程序中進行驗證? 驗證的文本框的標籤頁
這是我的表單應用程序
您可以使用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");
}
它會顯示對每個控制誤差(見以下快照)並不會提交表單。
[Winforms中的字段驗證](http:// stackoverflow。com/questions/3573302/fields-validation-in-winforms) – Shaharyar
我需要一個驗證中所有行的短代碼。不分隔每行 – Cristina
你需要什麼驗證?這是所有控件的「必需字段驗證」嗎? – Shaharyar