Have event fire whenever any changes made to textboxes, comboboxs, etc. inside form

后端 未结 4 1699
别跟我提以往
别跟我提以往 2021-01-13 03:52

I\'m working with a C# WinForm. It has more than a dozen text boxes, combo boxes, and check boxes. The winform displays information that is retrieved from a database. There

4条回答
  •  孤街浪徒
    2021-01-13 04:23

    Here is enough to get you stared. You may need to add extra foreach loops for other control types as needed. The nice thing is that you only need a few lines of code per Control type, not per instance, with this approach.

    private void addHandlers()
    {
        foreach (TextBox control in Controls.OfType())
        {
            control.TextChanged += new EventHandler(OnContentChanged);
        }
        foreach (ComboBox control in Controls.OfType())
        {
            control.SelectedIndexChanged += new EventHandler(OnContentChanged);
        }
        foreach (CheckBox control in Controls.OfType())
        {
            control.CheckedChanged += new EventHandler(OnContentChanged);
        }
    }
    
    protected void OnContentChanged(object sender, EventArgs e)
    {
        if (ContentChanged != null)
            ContentChanged(this, new EventArgs());
    }
    
    public event EventHandler ContentChanged;
    

    After modifying the addHandlers method to support all of your controls, and calling it after adding all of the controls to your form, you can simply subscribe to the ContentChanged event for doing whatever might need to happen anytime something on the form changed (i.e. enable/disable a save button).

提交回复
热议问题