我如何检查是否为空或空文本框多没有独特的测试每个? [英] How can I check multiple textboxes if null or empty without a unique test for each?
问题描述
我有一个表格,用户可以填写在大约20个文本字段。我想提示用户考虑节省,如果他们有什么类型到任何文本框。眼下的测试是很长而凌乱:
I have about 20 text fields on a form that a user can fill out. I want to prompt the user to consider saving if they have anything typed into any of the text boxes. Right now the test for that is really long and messy:
if(string.IsNullOrEmpty(txtbxAfterPic.Text) || string.IsNullOrEmpty(txtbxBeforePic.Text) ||
string.IsNullOrEmpty(splitContainer1.Panel2) ||...//many more tests
有没有一种方法,我可以使用类似的任何一个数组,数组由文本框,我检查呀?还有什么其他的方法可能会在其中,看是否已经作出任何改变,因为该方案开始了吗?一个非常方便的方式。
Is there a way I could use something like an Array of any, where the array is made of the text boxes and I check it that way? What other ways might be a very convenient way in which to see if any changes have been made since the program started?
我要提到的另一件事是有日期时间选择器。我不知道如果我需要测试不同,由于的DateTimePicker永远不会为空或空。
One other thing I should mention is there is a date time picker. I don't know if I need to test around that as the datetimepicker will never be null or empty.
编辑:
我合并的答案在我的计划,但我似乎无法使其正常工作。
我设置的测试如下,并保持触发Application.Exit()调用。
I incorporated the answers into my program, but I can't seem to make it work correctly. I set up the tests as below and keep triggering the Application.Exit() call.
//it starts out saying everything is empty
bool allfieldsempty = true;
foreach(Control c in this.Controls)
{
//checks if its a textbox, and if it is, is it null or empty
if(this.Controls.OfType<TextBox>().Any(t => string.IsNullOrEmpty(t.Text)))
{
//this means soemthing was in a box
allfieldsempty = false;
break;
}
}
if (allfieldsempty == false)
{
MessageBox.Show("Consider saving.");
}
else //this means nothings new in the form so we can close it
{
Application.Exit();
}
为什么不是基于code以上发现在我的文本框的任何文本?
Why is it not finding any text in my text boxes based on the code above?
推荐答案
当然 - 枚举通过你的控制寻找文本框:
Sure -- enumerate through your controls looking for text boxes:
foreach (Control c in this.Controls)
{
if (c is TextBox)
{
TextBox textBox = c as TextBox;
if (textBox.Text == string.Empty)
{
// Text box is empty.
// You COULD store information about this textbox is it's tag.
}
}
}
这篇关于我如何检查是否为空或空文本框多没有独特的测试每个?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!