大家好,我想以简单的方式找到所有空的 TextBox 和 ComboBox。 正如您在下图中看到的,如果字段为空,它们会显示消息和红色背景颜色,其中文本框或组合框为空。
我尝试了一些错误,感谢那些可以解决这个问题的人。
TextBox [] textBox = { textBox1, textBox2};
ComboBox[] comboBox = { comboBox1, comboBox2 };
foreach (TextBox txt in textBox)
{
if (string.IsNullOrEmpty(txt.Text))//if all textbox is empty
{
txt.BackColor = Color.Red;
string message = "Required field empty.";
string tittle = "Error";
MessageBoxButtons button = MessageBoxButtons.OK;
DialogResult result = MessageBox.Show(message, tittle, button, MessageBoxIcon.Error);
break;
}
else if (!string.IsNullOrEmpty(txt.Text))//if not empty
{
txt.BackColor = Color.White;
MessageBox.Show("task complete");
break;
}
}
return;
// Arrays to hold your TextBox and ComboBox controls
TextBox[] textBoxes = { textBox1, textBox2 };
ComboBox[] comboBoxes = { comboBox1, comboBox2 };
bool isEmpty = false; // Flag to indicate if any field is empty
// Check each TextBox
foreach (TextBox txt in textBoxes)
{
if (string.IsNullOrEmpty(txt.Text))
{
txt.BackColor = Color.Red;
isEmpty = true;
}
else
{
txt.BackColor = Color.White;
}
}
// Check each ComboBox
foreach (ComboBox cmb in comboBoxes)
{
if (string.IsNullOrEmpty(cmb.Text))
{
cmb.BackColor = Color.Red;
isEmpty = true;
}
else
{
cmb.BackColor = Color.White;
}
}
// Show a single message if any field is empty
if (isEmpty)
{
string message = "Required field empty.";
string title = "Error";
MessageBoxButtons buttons = MessageBoxButtons.OK;
MessageBox.Show(message, title, buttons, MessageBoxIcon.Error);
}
else
{
MessageBox.Show("Task complete");
}