35

I have a simple TextBox that is empty in the beginning. I have a simple event, _TextChanged, to know when the user changed anything in that TextBox. However, the event fires if I do anything with it myself from within code. Like setting textbox.Text = "Test"; or similar.

    private void textNazwa_TextChanged(object sender, EventArgs e) {
        changesToClient = true;
    }

How do I make the event only fire on user interaction and not code changes?

4
  • 4
    You can't it does not differentiate. Nov 27, 2011 at 19:47
  • Work around could be unsubscribing before manually editing a text but this is worst anyway
    – sll
    Nov 27, 2011 at 19:49
  • If your events are calling each other infinitely, you should change something else in the design. Either break the dependency cycle between the events, or add a stop condition. (E.g. for the TextChanged event, it's when the new text is the same as the old one - the event shouldn't get fired then.)
    – millimoose
    Nov 27, 2011 at 19:50
  • @Inerdial: This sort of thing is very common; the control itself does not ensure that the text has actually changed, just that the property itself was set. Nov 27, 2011 at 19:59

4 Answers 4

46

I've been using this process, and it seems to work well. If the event fires and the focus is not in the textbox, then I ignore the request, so when I set the text the focus is elsewhere, but when the user is typing in the textbox, it has the focus, so I acknowledge the changes.

private void textNazwa_TextCanged(object sender, EventArgs e)
{
    if ( !textNazwa.Focused) 
        return; 
}
4
  • 2
    Wow, this is quite ingenious. Sure there might be some rare case where you have binding updates triggered by a timer an the user happens to be using the control at the same time, but that would be terrible design to begin with. For my use-case this solution is the best. Aug 23, 2013 at 15:53
  • 1
    I like this too. I'm guessing it would work for checkboxes which is a real pain for me at the moment
    – userSteve
    Dec 5, 2014 at 17:24
  • textNazwa.Text="I changed"; // (textNazwa is focused) . This example fails if the textbox is focused while it's changed via code.
    – magallanes
    Mar 30, 2018 at 21:03
  • if (textNazwa.Focused) { //Do something } wrapping code like will only run if a user actually changed it manually. Aug 31, 2018 at 10:07
25

The event itself does not make a distinction between text entered via user input and text changed via code. You'll have to set a flag yourself that tells your code to ignore the event. For example,

private bool ignoreTextChanged;

private void textNazwa_TextCanged(object sender, EventArgs e)
{
    if (ignoreTextChanged) return;
}

Then use this to set the text instead of just calling Text = "...";:

private void SetTextboxText(string text)
{
    ignoreTextChanged = true;

    textNazwa.Text = text;

    ignoreTextChanged = false;
}

Judging by your comment to another answer, it sounds like you have quite a number of textboxes. In that case, you could modify the function in this way:

private void SetTextBoxText(TextBox box, string text)
{
    ignoreTextChanged = true;

    box.Text = text;

    ignoreTextChanged = false;
}

Then call it like this:

SetTextBoxText(textNazwa, "foo");

This would accomplish the same thing as just doing textNazwa.Text = "foo", but will set the flag letting your event handler know to ignore the event.

2
  • 2
    That's actually better idea then to disable/enable an event.
    – MadBoy
    Nov 27, 2011 at 19:51
  • I'm setting text in code for all textboxes at once so doing one time ignoreTextChanged = true; then false should be enough.
    – MadBoy
    Nov 27, 2011 at 19:55
6

Well you can't not really anyway. What you can do is remove the handler before you make your change and add it back after you've made the change.

e.g.

  textNazwa.TextChanged -= textNazwa_TextChanged;
  textbox.Text = "Test";
  textNazwa.TextChanged += textNazwa_TextChanged;

If your method has the same scope as where you're changing the value of the text box as the textNazwa_TextChanged (e.g. both are in a form) you could set a flag instead or if that's not oopsy enough for you, you could use Chain Of Responsiblity to determine if the textNazwa_TextChanged method should be called

2
  • So if I have 30+ textboxes, couple of checkboxes with _TextChanged all I can do is go one by one and disable them ... and then enable..
    – MadBoy
    Nov 27, 2011 at 19:50
  • Or set a flag or use Chain Of Responsibility Nov 27, 2011 at 19:54
2

I suggest you use Bindings for your TextBox with a presenter that has properties, so if you need to change your values in the code (for testing for example) you don't to fire events or change to UI code. The only thing you need to do is to set a value on your Presenter.

public class Presenter : INotifyPropertyChanged
{
    public string MyTextValue { get; set; }
    public event PropertyChangedEventHandler PropertyChanged;
    /// Create a method here that raises the event that you call from your setters..
}

And then in you Windows Forms code you need a bindingSource set to your Presenter, and add a Binding to you textBoxes:

EDIT

private BindingSource myPresenterSource ;
this.myPresenterSource = new System.Windows.Forms.BindingSource(this.components);
// Some time later in the

((System.ComponentModel.ISupportInitialize)(this.myPresenterSource )).BeginInit();
// you set the DataSource of your BindingSource
// m_SettingsBindingSource
//
this.myPresenterSource .DataSource = typeof(Presenter );

// and when you create your TextBox you do this :
this.YourTextBox.DataBindings.Add(new System.Windows.Forms.Binding("Text",
   this.myPresenterSource, "MyTextValue", true,
   System.Windows.Forms.DataSourceUpdateMode.OnPropertyChanged));

Then in your InitializeComponent you set the source like this :

myPresenterSource.DataSource = new Presenter();

Check more resources by looking for how to implement the Movel-View-Presenter (MVP) in Windows Forms.

2
  • Sure if you can show one then great. I'm trying to learn Entity Framework to fill WinForm and then after user presses Save save changes back to database.
    – MadBoy
    Nov 27, 2011 at 20:04
  • So you EntityFramework could be the Model, and then you wrap it with a Presenter and you set the Presenter to the BindingSource as I described it. You should need have to change values for UI element "manually"
    – MBen
    Nov 27, 2011 at 20:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.