我需要有关如何制作和使用在多个文本框中检查多个内容的类的帮助。
现在我的问题是我有大约50个文本框,我已经为每一个添加了我需要的代码。 我向某人展示了我的代码,他告诉我我可以创建一个类,例如“Validation”,只需为我需要的每一个验证添加一个方法,只需使用class.methodname代替每行的多行代码文本框
现在我的问题是: - 如何从头开始创建这样的类? - 我如何在我的代码中实际使用这个类? - 如何添加方法来检查文本框是否为空? - 如何添加方法来检查文本框是否只包含字母/数字和空格,即使文本粘贴到文本框中也是如此? - 如何添加方法来检查文件夹是否已存在?
我目前添加到需要这些验证的每个文本框中的代码如下:
检查文本框是否为空
if (txtName.Text.Trim().Length == 0)
{
MessageBox.Show("Please enter a name!", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
检查文本框是否包含字母数字字符,但不适用于粘贴的文本
private void txtName_KeyDown(object sender, KeyEventArgs e)
{
if ((e.Key < Key.A) || (e.Key > Key.Z))
e.Handled = true;
}
最后检查文件夹是否已存在
string folderName = "";
bool exists= false;
folderName = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), txtName.text);
exists= System.IO.Directory.Exists(folderName);
if (exists)
{
MessageBox.Show("This name is already in use", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else
{
System.IO.Directory.CreateDirectory(folderName);
}
提前感谢您的帮助!
答案 0 :(得分:0)
而不是类MyTextBox
继承自TextBox
并使用this
来引用CurrentTextBox
在您想要的代码中使用此MyTextBox
class MyTextBox : TextBox
{
public bool IsMyTextBoxEmpty()
{
if (!string.IsNullOrEmpty(this.Text.Trim()))
{
return true;
}
return false;
}
public bool IsContainsValideSpaces()
{
//...........Your Logic is Here
return false;
}
public bool IsCopied()
{
//...........Your Logic is Here
return false;
}
}