您可以通过选择表单的所有控件
this.Controls
,然后使用LINQ进行过滤
Where
只取
TextBox
或
ComboBox
控件,以及
.Text
属性为空。
using System;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
// ...
private void ButtonSubmit_Click(object sender, EventArgs e)
{
// Find and take from all controls of the form only TextBox'es and ComboBox'es, which .Text is empty
var unfilledControls = this.Controls.Cast<Control>()
.Where(c => c is TextBox or ComboBox && string.IsNullOrEmpty(c.Text))
.ToList();
// Check if there was found unfilled controls
if (unfilledControls.Count == 0)
{
// Here you can proceed submit
// DoSubmit();
// MessageBox.Show("Submitted!");
// this.Close(); // to close form, or...
return;
}
// Here something is unfilled, so apply "warning" to control(s) or notify user
unfilledControls.ForEach(c => c.BackColor = Color.Red);
MessageBox.Show("Some required fields are empty!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
看起来像:
您还可以通过设置“警告”行为
TextChanged
属性,例如,在形式构造函数中。只需将匿名委托应用于该事件。所以它会改变
BackColor
并“动态”检查用户输入。
public Form3()
{
InitializeComponent();
this.Controls.Cast<Control>()
.Where(c => c is TextBox or ComboBox)
.ToList()
.ForEach(control =>
{
control.TextChanged += delegate
{
control.BackColor = string.IsNullOrEmpty(control.Text)
? Color.Red
: Color.White;
};
});
}