【发布时间】:2016-09-03 01:45:50
【问题描述】:
总的来说,我对 Visual Studio 和 C# 还很陌生,但基本上我需要检查文本框的内容是否有效,然后再继续使用按钮将内容添加到列表中。
我正在使用以下对象: 用于输入值的 TexBox 链接到 TextBox 以验证数据的 Validating 事件。 一个按钮来采取行动 与按钮关联的 Click 事件。
问题是我无法检查框中的值是否有效并阻止按钮中的单击事件发生。换句话说,如果内容无效,则不要采取行动。
这是我的代码。
public partial class mainForm : Form
{
public mainForm()
{
InitializeComponent();
}
private void addButton_Click(object sender, EventArgs e)
{
// I need to check if the content is valid before adding it to the form
ListViewItem item = new ListViewItem(this.nameTextBox.Text);
this.listView1.Items.Add(item);
}
private void nameTextBox_Validating(object sender, CancelEventArgs e)
{
int maxCharacters = 15;
String err = "";
String contents = this.nameTextBox.Text;
if (contents.Length == 0)
{
err = "I am sorry but the name cannot be empty";
e.Cancel = true;
}
else if (!contents.Replace(" ", "").Equals(contents, StringComparison.OrdinalIgnoreCase))
{
err = "I am sorry but the name cannot contain spaces";
e.Cancel = true;
}
else if (contents.Length > 15)
{
err = "I am sorry, but the name cannot have more than " + maxCharacters + " characters";
e.Cancel = true;
}
this.mainFormErrorProvider.SetError(this.nameTextBox, err);
}
}
【问题讨论】:
-
你没有意义..当你点击按钮是你想要调用验证事件的时候..或者你可以在该文本框的离开事件上执行它,这里有几个选项..
标签: c# visual-studio validation c#-4.0 visual-c++