Fuz*_*ans 9 c# arrays testing text isnullorempty
我在表单上有大约20个文本字段,用户可以填写.我想提示用户在任何文本框中输入任何内容时都要考虑保存.现在,对它的测试真的很长而且很混乱:
if(string.IsNullOrEmpty(txtbxAfterPic.Text) || string.IsNullOrEmpty(txtbxBeforePic.Text) ||
string.IsNullOrEmpty(splitContainer1.Panel2) ||...//many more tests
Run Code Online (Sandbox Code Playgroud)
有没有办法可以使用类似于任何数组的数组,其中数组是由文本框组成的,我是这样检查的?还有哪些方法可以非常方便地查看自程序启动以来是否有任何更改?
我应该提到的另一件事是有一个日期时间选择器.我不知道是否需要测试它,因为datetimepicker永远不会为null或为空.
编辑:我将答案纳入我的程序,但我似乎无法使其正常工作.我按如下所示设置测试并继续触发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();
}
Run Code Online (Sandbox Code Playgroud)
为什么根据上面的代码在我的文本框中找不到任何文本?
Geo*_*ton 26
当然 - 通过控件枚举查找文本框:
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.
}
}
}
Run Code Online (Sandbox Code Playgroud)
Str*_*ior 11
以George的答案为基础,但利用一些方便的LINQ方法:
if(this.Controls.OfType<TextBox>().Any(t => string.IsNullOrEmpty(t.Text)))
{
//Your textbox is empty
}
Run Code Online (Sandbox Code Playgroud)