Is there a way to find out if the "TextChanged" event is fired because
- the user is typing into a textbox or
- the programmer called myTextBox.Text = "something"?
Just to give you some color on this, I don't want to react when the user is typing each letter into the textbox so I am using the "Validated" event to catch when the user is done so I can react. The problem is I don't have a way to catch when the programmer does "myTextbox.Text = "something". The only way I know to catch changes there is to use TextChanged but then I don't want to be reacting when the user is typing each letter into the textbox. Any suggestions?
The event handler is called whenever the contents of the TextBox control are changed, either by a user or programmatically. This event fires when the TextBox control is created and initially populated with text.
The TextChanged event is raised when the content of the text box changes between posts to the server.
Text box controls allow entering text on a form at runtime. By default, it takes a single line of text, however, you can make it accept multiple texts and even add scroll bars to it.
So in your "Formatted" Textbox class:
public override String Text{
get{return text;}
set
{
//perform validation/formatting
this.text = formattedValue;
}
this should allow you to format the text when it is changed by a programmer, the user input validation will still need to be handled in the validating event.
I will guess that you're creaing a UserControl that other developers will use, thus "end-user" programmers may set the text programmatically. I think the simplest thing would be to follow @jzworkman's suggestion and make a class that overrides the Text property setter. As @vulkanino notes, you should probably raise and catch the Validating event, though.
public class TextBoxPlus : TextBox {
public event CancelEventHandler ProgrammerChangedText;
protected void OnProgrammerChangedText(CancelEventArgs e) {
CancelEventHandler handler = ProgrammerChangedText;
if (handler != null) { handler(this, e); }
}
public override string Text {
get {
return base.Text;
}
set {
string oldtext = base.Text;
base.Text = value;
CancelEventArgs e = new CancelEventArgs();
OnProgrammerChangedText(e);
if (e.Cancel) base.Text = oldtext;
}
}
}
In your source, add the same handler to both the Validating and ProgrammerChangedText events:
// Somewhere...
textBoxPlus1.Validating += textBoxPlus1_Validating;
textBoxPlus1.ProgrammerChangedText += textBoxPlus1_Validating;
void textBoxPlus1_Validating(object sender, CancelEventArgs e) {
decimal d;
if (!Decimal.TryParse(textBoxPlus1.Text, out d)) {
e.Cancel = true;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With