【发布时间】:2016-06-27 09:47:17
【问题描述】:
所以我写了一个代码来检查我的表单中是否有任何字段为空。我有多个表单,我必须在其中几个中使用这个验证检查。我想把它写成一个全局函数,所以我没有'不必一次又一次地编写相同的代码行。但是代码包含对“this”的引用。如何采用将其作为参数调用的表单类,以便我可以使代码全局化。这是我的代码:
// Checks if any field is empty.
foreach (Control ctrl in this.Controls)
{
// Checking if it is a textbox.
if (ctrl is TextBox)
{
TextBox txtbx = ctrl as TextBox;
if (txtbx.Text == String.Empty)
{
MessageBox.Show("Please fill all the fields.", "Empty Fields", MessageBoxButtons.OK, MessageBoxIcon.Warning);
txtbx.Focus();
}
}
// Checking if it is a combobox.
else if (ctrl is ComboBox)
{
ComboBox cmbbx = ctrl as ComboBox;
if (cmbbx.Text == String.Empty)
{
MessageBox.Show("Please fill all the fields.", "Empty Fields", MessageBoxButtons.OK, MessageBoxIcon.Warning);
cmbbx.Focus();
}
}
}
要对代码进行哪些更改,以便可以全局使用。例如,可以这样调用它:
ValidateForm(this);
或者有更好的方法吗?
【问题讨论】:
-
是的,你可以做 ValidateForm(this);但是应该将 ValidateForm 声明为广告 ValidateForm(Form form) 然后将所有“this”更改为“form”
-
@Malin 感谢哥们的帮助,我找到了解决办法。
标签: c# function class parameters global