简体   繁体   English

遍历控件以查找errorProviders c#WinForm

[英]Iterate through Controls to find errorProviders c# WinForm

Overview of function. 功能概述。

I have this SaveDetails function within a WinForm , which iterates through all of the controls , to determine whether any errorProviders have been flagged in the form during the users input. 我在WinForm具有此SaveDetails函数,该函数循环访问所有controls ,以确定在用户输入期间是否在form中标记了任何errorProviders If the function returns true , all of my TextBoxes values need to be stored in my private fields, and display a messsagebox and close the form. 如果函数returns true ,则我的所有TextBoxes值都需要存储在我的私有字段中,并显示消息框并关闭表单。

// For about 15 textBoxes, Could this be achieved also by looping? //对于大约15个textBox,也可以通过循环实现吗? As this looks very cumbersome. 因为这看起来很麻烦。

title = cmb_Title.Text;  

If returns false and an errorProvider has been found in the iteration, it needs to display an error message for the user, clear private fields and give the user chance to re-enter details, however not clear textBoxes!! 如果returns false并在迭代中找到errorProvider ,则它需要为用户显示一条错误消息,清除私有字段并为用户提供重新输入详细信息的机会,但不能清除textBoxes!

Issue : 问题

the loop iterates through everything, all of the controls regardless if it has found an errorProvider . 循环遍历所有控件,无论是否找到errorProvider How can I stop this to just flag when just one has been found? 找到一个后,如何停止此操作以仅进行标记? This function is also in a clickEvent . 该函数也在clickEvent

Code

isValid = true;
                foreach (Control c in panel1.Controls)
                {
                    if (errorProvider1.GetError(c).Length > 0)
                    {
                        isValid = false;
                        MessageBox.Show("invalid entry, please revisit the form before proceding");

                    }
                }
                if (isValid)
                {
                    title = cmb_Title.Text;
                    surName = txt_SurName.Text;
                    dateOfBirth = dateTimePicker1.Text.ToString();


                    MessageBox.Show("Indi Form Saved");
                    Hide();

you can shorten it using only TextBox controls and Linq. 您可以仅使用TextBox控件和Linq来缩短它。

Something like this: 像这样:

List<TextBox> textBoxes = panel1.Controls.OfType<TextBox>().ToList();
if (textBoxes.Any(tb => !string.IsNullOrEmpty(errorProvider1.GetError(tb))))
    MessageBox.Show("invalid entry, please revisit the form before proceding");

If you don't want to check only TextBox controls but all controls in panel1 , you can still use Linq to simplify your code. 如果您不想只检查TextBox控件,而是只检查panel1所有控件,则仍然可以使用Linq来简化代码。

var controlsList = panel1.Controls.Cast<Control>().ToList();
if (controlsList.Any(tb => !string.IsNullOrEmpty(errorProvider1.GetError(tb))))
    MessageBox.Show("invalid entry, please revisit the form before proceding");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM