[英]Regex for textChanged event of TextBox
在我的項目中,有很多TextBoxes
里面TabControl
到我賜相同的事件是這樣的:( 工作 )
在我的表單構造函數中:
SetProperty(this);
private void SetProperty(Control ctr)
{
foreach (Control control in ctr.Controls)
{
if (control is TextBox)
{
control.TextChanged += new EventHandler(ValidateText);
}
else
{
if (control.HasChildren)
{
SetProperty(control); //Recursive function if the control is nested
}
}
}
}
現在,我嘗試將TextChanged事件提供給所有TextBoxes。 像這樣的東西:
private void ValidateText(object sender,EventArgs e)
{
String strpattern = @"^[a-zA-Z][a-zA-Z0-9\'\' ']{1,20}$"; //Pattern is Ok
Regex regex = new Regex(strpattern);
//What should I write here?
}
我不知道在上面的方法中寫什么,因為沒有要考慮的文本框。 請提出建議。
編輯:我提到的模式不應該允許進入TextBoxes,即Text應該自動轉換為匹配的字符串。 (應該禁止我在模式中提到的字符)。
您應該首先獲取調用TextBox
的引用,然后可以匹配正則表達式進行驗證以做出所需的任何決定。
private void ValidateText(object sender, EventArgs e)
{
TextBox txtBox = sender as TextBox;
String strpattern = @"^[a-zA-Z][a-zA-Z0-9\'\' ']{1,20}$"; //Pattern is Ok
Regex regex = new Regex(strpattern);
if (!regex.Match(txtBox.Text).Success)
{
// passed
}
}
另外 ,更好的方法是掛起Validating
事件,您可以在希望一次對所有TextBoxes
執行一次Validation的任何時間調用此事件。
private void SetProperty(Control ctr)
{
foreach (Control control in ctr.Controls)
{
if (control is TextBox)
{
control.Validating += ValidateText;
}
else
{
if (control.HasChildren)
{
SetProperty(control); //Recursive function if the control is nested
}
}
}
}
private void ValidateText(object sender, CancelEventArgs e)
{
TextBox txtBox = sender as TextBox;
String strpattern = @"^[a-zA-Z][a-zA-Z0-9\'\' ']{1,20}$"; //Pattern is Ok
Regex regex = new Regex(strpattern);
//What should I write here?
if (!regex.Match(txtBox.Text).Success)
{
e.Cancel = true;
}
e.Cancel = false;
}
要執行驗證,請調用此方法:
bool isValid = !this.ValidateChildren(ValidationConstraints.Enabled);
參考文獻:
您還可以將文本框控件this.textbox1發送到事件處理程序方法,並在事件處理程序中使用正則表達式檢查該控件的輸入文本。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.