[英]Verifying Controls on a Windows Form
I have a windows from written in C# and wanted to verify that the data in each control (dropdown, textbox, etc) is not null before saving the data to a database. 我有一个用C#编写的Windows,想要在将数据保存到数据库之前验证每个控件(下拉菜单,文本框等)中的数据是否不为null。 I have multiple forms like this in the application.
我在应用程序中有多种形式。 How would I go about doing it?
我将如何去做? I am thinking I create boolean function.
我在想我创建布尔函数。
You can write a simple method to loop through the controls in the form and check the control values. 您可以编写一种简单的方法来循环浏览表单中的控件并检查控件值。
private bool CheckControls()
{
foreach (Control ctrl in this.Controls)
{
//Write the code to check whether the control value is null
//case: Testbox return true;
//case: Dropdown return true;
//case: Listbox return true;
//..etc
}
return false;
}
use an ErrorProvider. 使用一个ErrorProvider。 Put the error provider on the form and then you can have a utility function that can handle all the controls with one call.
将错误提供程序放在窗体上,然后您可以使用一个实用程序函数,该函数可以通过一次调用处理所有控件。 I used the following code for making sure something was entered in a textbox, you can expand upon this method.
我使用以下代码来确保在文本框中输入了某些内容,您可以在此方法上进行扩展。
Utility method that handled required fields, I used the tag field to hold the specific error message since I wasn't using it for anything else and it was quick and easy. 用于处理必填字段的实用程序方法,我使用标记字段来保存特定的错误消息,因为我没有将其用于其他任何事情,并且它既快速又容易。
public static void TextBoxRequired_Validating(object sender, CancelEventArgs e, ErrorProvider errorProvider)
{
var textbox = (TextBox)sender;
var valid = !String.IsNullOrWhiteSpace(textbox.Text);
e.Cancel = !valid;
errorProvider.SetError(textbox, (valid ? string.Empty : textbox.Tag.ToString()));
}
The event handler calling the utility method 调用实用程序方法的事件处理程序
void txtName_Validating(object sender, CancelEventArgs e)
{
ControlUtility.TextBoxRequired_Validating(sender, e, errorProvider1);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.