Cómo saber si el evento "TextChanged" se activa si el usuario está escribiendo en un cuadro de texto o myTextBox.Text se llama mediante programación

Is there a way to find out if the "TextChanged" event is fired because

  1. the user is typing into a textbox or
  2. 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?

preguntado el 09 de marzo de 12 a las 15:03

?? aren't the programmers under your control? -

What is the context that you need to validate programmer input for your textbox like this? Shouldn't the programmer know what is valid input and be checking that before setting the text to something? A simple validation could be added to the myTextbox.Text property(override the default Text property) as well if you dont want the check to be performed in each place in the code where the text is set. -

I am creating a "Formatted" textbox which will render the text in the textbox with a format string when the textbox's text has been entered (like a mask but more customizable) -

To deal with typing, use the key_down or key_pressed events. -

@Denis then you can override the set method of the Text Property of your formatted textbox. This will allow you to format the string whenever myTextBox.Text = "something" se llama -

4 Respuestas

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.

respondido 09 mar '12, 16:03

Exactly! So simple, just didn't think of it... No idea why people are marking this down... This is exactly what I was looking for - looking at events was the wrong way - I needed to tune my brain to a different station and look at overriding properties/methods. - Denis

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 Validación 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;
    }
}

respondido 09 mar '12, 16:03

I dont know why someone downvoted you so I added an upvote since this is a well thought out answer and limits the code re-use - jzworkman

This is the way I went in the end with the RaiseEvent (same as @jzworkman with the "RaiseEvent" feature). Wish I could mark both as answers. Thank you. - Denis

If you want to perform validation, use the Validating evento, no el Validated (which comes when it is too late to act).

That said, what's the reales need here?

The Validating event is supplied an object of type CancelEventArgs. If you determine that the control's data is not valid, you can cancel the Validating event by setting this object's Cancel property to true. If you do not set the Cancel property, Windows Forms will assume that validation succeeded for that control, and raise the Validated event.

(http://msdn.microsoft.com/en-us/library/ms229603.aspx)

respondido 09 mar '12, 15:03

Validating/Validated events DO NOT fire when you are doing myTextBox.Text = "something" so this doesn't work. - Denis

// This is the manual way, which is an alternative to the first way.
// Type 'this.TextChanged += ' into your form's constructor.
// Then press TAB twice, and you will have a new event handler.
this.TextChanged += new EventHandler(textBox1_TextChanged);

void textBox1_TextChanged(object sender, EventArgs e)
{
    //put the logic here for your validation/requirements for validation
    // ex.  if (textbox1.Text=="something") {//don't validate}
    //
}

respondido 09 mar '12, 15:03

This will be called each time a user types a new character into the textbox which the OP does not want. He wants when the myTextbox.Text property is set to something new. - jzworkman

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.