Passing a textbox to a void
I'm not sure if I'm using the wrong terminology so that may be why my searching has not turned up anything.
I have a bunch of text boxes that I want to validate and check that they don’t contain apostrophes. The code that I have is:
开发者_运维百科public void apostropheCheck(TextBox fieldName)
{
Match m = Regex.Match(fieldName.Text, @"'");
if (m.Success)
{
validationErrorProvider.SetError(fieldName, "Field can not contain apostrophes");
}
else if (!m.Success)
{
validationErrorProvider.SetError(fieldName, "");
}
}
and the validation on the textbox is:
private void FirstNameTextBox_Validating(object sender, System.ComponentModel.CancelEventArgs e)
{
//Checks for apostrophes
apostropheCheck(FirstNameTextBox);
}
However when I run this the value that gets passed to the void is the text that is in the text box (e.g ‘John’ or ‘Mary’) I could get this to work just using the code that’s in the void for each validation event but that would be repeating myself a lot. Is there a better way?
You can have one common handler and use that for all of the textboxes' Validating
event.
private void CommonTextBox_Validating(object sender, System.ComponentModel.CancelEventArgs e)
{
//Checks for apostrophes
apostropheCheck((TextBox)sender);
}
The sender object of the event is a TextBox, so you can cast it to a text box and repeat the same event handler for all of the text boxes in your application
private void FirstNameTextBox_Validating(object sender, System.ComponentModel.CancelEventArgs e)
{
apostropheCheck(((TextBox)sender).Text);
}
Terminology: you are referring to your function
apostropheCheck
as the void which is its return type the standard way is to use the function name apostropheCheck.All of you text boxes can be validated using the same function if you replace the name of the text box in the code with sender ex.
private void FirstNameTextBox_Validating(object sender,System.ComponentModel.CancelEventArgs e) { //Checks for apostrophes apostropheCheck((TextBox)sender); }
精彩评论