[英]How To Detect If All Textboxes Are Empty When Clicked Save Button
I have a question about there are 30 textboxes on a windows form.我有一个关于 windows 表单上有 30 个文本框的问题。 I am trying to test the application.
我正在尝试测试应用程序。
All textboxes have validation event for you enter, keypresses and leave events.所有文本框都有验证事件供您输入、按键和离开事件。
But the problem when open the page and directly pressed the button it saves textboxess without warning.但是打开页面并直接按下按钮时会出现问题,它会在没有警告的情况下保存文本框。
How to handele all textboxes empty situation without checking each of them with conditions like如何在不检查每个文本框的情况下处理所有文本框为空的情况,例如
if(String.isNotNullorEpty(textbox1.Text)&&...)
thanks.谢谢。
You can simply loop thru all textbox controls and check if one of them has text.If only 1 out of 30 has text then your condition is false.您可以简单地循环遍历所有文本框控件并检查其中一个是否有文本。如果 30 个中只有 1 个有文本,那么您的条件为假。
bool allEmpty = true;
foreach (Control c in Controls)
{
if(c is TextBox tb && !String.IsNullOrEmpty(tb.Text))
{
allEmpty = false;
break;
}
}
Using linq:使用 linq:
bool allEmpty = parentControl.Controls.OfType<TextBox>().All(tb => tb.Text == "");
Just set your 'parentControl'.只需设置你的'parentControl'。
There is no need to check all textboxes, or any other loop.无需检查所有文本框或任何其他循环。
Keep your save changes button
disabled.禁用
save changes button
。 You have events for every textbox already, just add to this events to enable the save changes button
when text is changing.您已经为每个文本框设置了事件,只需添加到此事件以在文本更改时启用
save changes button
。 This way it is not possible anymore to save changes immediate when the form has opened这样就不可能在表单打开时立即保存更改
Another advantage of this method is that when the user closes the form you can check if there are any unsaved changes, and ask if he wants to save them before closing.这种方法的另一个优点是,当用户关闭表单时,您可以检查是否有任何未保存的更改,并在关闭前询问他是否要保存它们。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.