[英]TextBox Validation in Visual Studio C#
一般而言,我對Visual Studio和C#還是相當陌生,但是基本上我需要先檢查文本框的內容是否有效,然后再將內容添加到帶有按鈕的列表中。
我正在使用以下對象:一個TexBox輸入值一個Validating事件鏈接到TextBox以驗證數據。 采取措施的按鈕與該按鈕關聯的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);
}
}
您對何時調用“名稱”文本框的驗證方法感到困惑。
看這里
當您使用鍵盤(TAB,SHIFT + TAB等),通過調用Selector SelectNextControl方法或將ContainerControl.ActiveControl屬性設置為當前窗體來更改焦點時,焦點事件將按以下順序發生。 。
因此,單擊按鈕與文本框的驗證無關 。
您需要做的是將驗證邏輯放在單獨的方法中,然后從兩個事件中調用它 。
另外,由於您不熟悉C#,因此這里有一些指針。
命名空間,類,方法和屬性應該是Pascal Case 。
而不是像這樣漫長的工作
!contents.Replace(" ", "").Equals(nameText, StringComparison.OrdinalIgnoreCase)
您可以簡單地使用
contents.Contains(" ")
這里有很多有用的方法就是這樣,所以在未來,你應該做更多的研究,你自己的東西實現,尤其是如果它看起來像一個常用的技術之前,需要什么。
另外,您也希望盡可能避免if / else,而希望早日返回。
考慮更好的練習,這就是您的班級外觀
const int NAME_MAX_CHARACTERS = 15;
public mainForm()
{
InitializeComponent();
}
private void addButton_Click(object sender, EventArgs e)
{
if(!Validate())
{
return;
}
// 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)
{
e.Cancel = !Validate();
}
private bool Validate()
{
string nameText = nameTextBox.Text;
if(String.IsNullOrEmpty(nameText))
{
this.mainFormErrorProvider.SetError(this.nameTextBox, "I am sorry but the name cannot be empty");
return false;
}
if(nameText.Contains(" "))
{
this.mainFormErrorProvider.SetError(this.nameTextBox, "I am sorry but the name cannot contain spaces");
return false;
}
if (nameText.Length > 15)
{
this.mainFormErrorProvider.SetError(this.nameTextBox, "I am sorry, but the name cannot have more than " + NAME_MAX_CHARACTERS + " characters");
return false;
}
return true;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.