我有一个表单上大约有20个文本框,用户可以填写。如果他们在任何一个文本框中输入了任何内容,我想提示用户考虑保存。目前这个测试非常冗长而混乱:
if(string.IsNullOrEmpty(txtbxAfterPic.Text) || string.IsNullOrEmpty(txtbxBeforePic.Text) ||
string.IsNullOrEmpty(splitContainer1.Panel2) ||...//many more tests
我能否使用类似任意类型数组的内容,其中该数组由文本框组成,并通过这种方式进行检查?还有哪些其他非常方便的方法可以用来查看自程序启动以来是否有任何更改?
还有一件事情要提到的是,有一个日期时间选择器。我不知道是否需要在该日期时间选择器周围进行测试,因为datetimepicker永远不会为空。
编辑: 我将答案添加到我的程序中,但似乎无法正常工作。 我按以下方式设置了测试,并不断触发Application.Exit()调用。
//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();
}
为什么基于以上代码,我的文本框中没有找到任何文本?