Fire events when any changes made to text fields, drop-down lists, etc. Inside form

I am working with C # WinForm. It contains more than a dozen text fields, combo boxes and flags. Winform displays information retrieved from the database. In the disabled form there is a save button. I want to be able to enable it when any of the text fields / combo boxes / flags are changed.

Is there an easy way to do this without adding separate event handlers to each of these elements?

+5
source share
4 answers

Itโ€™s enough for you to watch. You may need to add additional loops foreachfor other types controlas needed. It's nice that you only need a few lines of code for the type control, and not for each instance, with this approach.

private void addHandlers()
{
    foreach (TextBox control in Controls.OfType<TextBox>())
    {
        control.TextChanged += new EventHandler(OnContentChanged);
    }
    foreach (ComboBox control in Controls.OfType<ComboBox>())
    {
        control.SelectedIndexChanged += new EventHandler(OnContentChanged);
    }
    foreach (CheckBox control in Controls.OfType<CheckBox>())
    {
        control.CheckedChanged += new EventHandler(OnContentChanged);
    }
}

protected void OnContentChanged(object sender, EventArgs e)
{
    if (ContentChanged != null)
        ContentChanged(this, new EventArgs());
}

public event EventHandler ContentChanged;

After changing the method addHandlersto support all your controls and invoking it after adding all the controls to your form, you can simply subscribe to the event ContentChangedto perform any actions that may occur at any time the form has changed (i.e. enable / disable the save button) .

+5
source

. .

private void AssignHandlersForControlCollection(
       Control.ControlCollection coll)
  {
      foreach (Control c in coll)
      {
          if (c is TextBox)
              (c as TextBox).TextChanged 
                += new EventHandler(SimpleDirtyTracker_TextChanged);

          if (c is CheckBox)
              (c as CheckBox).CheckedChanged 
                += new EventHandler(SimpleDirtyTracker_CheckedChanged);

          // ... apply for other desired input types similarly ...

          // recurively apply to inner collections
          if (c.HasChildren)
              AssignHandlersForControlCollection(c.Controls);
      }
  }
+2

, , , , , Visual Studio ( ).

0

, , , bool mbSomethingChanged = true . , .

0

All Articles