How to detect changes in any control of the form?

后端 未结 3 2551

How can I detect changes in any control of the form in C#?

As I have many controls on one form and i need to disable a button if any of the control value in the form ch

相关标签:
3条回答
  • 2021-02-20 18:18

    Instead of accessing the controls directly you can databind to a model object that implements INotifyPropertyChanged.

    Whenever the user does something that causes the data in your model to change you will be notified and can take the appropriate action.

    It will probably also cut down on the amount of code you need to get values in and out of the form controls.

    0 讨论(0)
  • 2021-02-20 18:19

    No, I'm not aware of any event that fires whenever any control on the form changes.

    My advice would be to subscribe to each event individually (if your form has so many controls that this is actually difficult to do, then you may want to re-think your UI).

    If you absolutely must subscribe to changes to all controls then you might want to consider something similar to the following:

    foreach (Control c in this.Controls)
    {
        c.TextChanged += new EventHandler(c_ControlChanged);
    }
    
    void c_ControlChanged(object sender, EventArgs e)
    {
    
    }
    

    Note that this wouldn't work particularly well however if you dynamically add and remove controls to the form at runtime.

    Also, the TextChanged event might not be a suitable event for some control types (e.g. TextBoxes) - in this case you will need to cast and test the control type in order to be able to subscribe to the correct event, e.g.:

    foreach (Control c in this.Controls)
    {
        if (c is CheckBox)
        {
            ((CheckBox)c).CheckedChanged += c_ControlChanged;
        }
        else
        {
            c.TextChanged += new EventHandler(c_ControlChanged);
        }
    }
    
    0 讨论(0)
  • 2021-02-20 18:25

    Simply select the components that will have common handler and in the events property bar double click to event that you want to occur. This common method will be added automatically to all control's handlers.

    0 讨论(0)
提交回复
热议问题