问题描述
我正在尝试使用错误提供程序实施以在继续执行之前验证我的文本框是否为空.
I am trying to implement using error provider to validate that my text boxes are not empty before proceeding with execution.
错误提供程序可在主窗体上的文本框上使用,但拒绝在组框或tabcontrol中的任何文本框或组合框上使用.它不会选中文本框,不会显示错误,也不会等到用户为要检查的控件输入文本/选择项.
Error provider works on textboxes on the main form but refuses to work on any textbox or combo box that is in a groupbox or tabcontrol. It doesn't check the text boxes, it doesn't display error or waits until the user enter text/select item for the controls that are being checked.
当然,如果我松开groupbox或tabcontrol,我将获得正常的错误检查,但我也将失去按我的意愿对应用程序使用groupbox和tab控件的好处.
Sure if I loose the groupbox or tabcontrol I would get the error check working as normal but I will also loose the benefit of using the groupbox and tab control for my application as I intended to.
我正在使用下面的代码检查文本框或组合框是否为空/空.
I am using the code below to check if the textbox or combo box is empty/null.
一些帮助将不胜感激,这使我几乎想把我的计算机扔到窗外.
Some help would be much appreciated, this has made me almost want to throw my computer out of the window.
private void button3_Click(object sender, EventArgs e)
{
//Validate the text box in the form before proceeding to store in Database
// var emptyornull = Controls.OfType<TextBox>().Where(box => box.Name.StartsWith("_")).OrderBy(box => box.TabIndex);
// var emptyornull2 = Controls.OfType<ComboBox>().Where(box => box.Name.StartsWith("_")).OrderBy(box => box.TabIndex);
var boxes = Controls.OfType<TextBox>();
foreach (var testControl in boxes)
{
if (string.IsNullOrEmpty(testControl.Text))
{
this.errorProvider1.SetError((Control)testControl, "error");
return;
}
this.errorProvider1.SetError((Control)testControl, (string)null);
}
}
推荐答案
这是因为您的代码不会检查子控件,而只会检查顶级控件.您需要递归地遍历窗体的控件:
This is because your code does not check the child controls and only checks the top level ones. You need to iterate through the Form's controls recursively:
private IEnumerable<Control> GetAllControls(Control control)
{
var controls = control.Controls.Cast<Control>();
return controls.SelectMany(ctrl => GetAllControls(ctrl)).Concat(controls);
}
private void button1_Click(object sender, EventArgs e)
{
errorProvider1.Clear();
foreach (Control c in GetAllControls(this))
{
if (c is TextBox && string.IsNullOrEmpty(c.Text))
errorProvider1.SetError(c, "Error");
}
}
或者,用Linq方式:
Or, Linq way:
errorProvider1.Clear();
GetAllControls(this).Where(c => c is TextBox && string.IsNullOrEmpty(c.Text))
.ToList()
.ForEach(c => errorProvider1.SetError(c, "Error"));
祝你好运.
这篇关于C#错误提供程序不适用于groupbox和tabcontrols中的文本框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!