有火灾事件每当有文本框所做的任何更改,comboboxs等内部形状 [英] Have event fire whenever any changes made to textboxes, comboboxs, etc. inside form

查看:166
本文介绍了有火灾事件每当有文本框所做的任何更改,comboboxs等内部形状的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用C#WinForm的工作。它有十几个文本框,组合框和复选框等等。是从一个数据库中检索到的WinForm的显示信息。还有就是禁用窗体上的保存按钮。我希望能够使其能够在任何文本框/组合框/复选框被改变。

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 is a save button on the form that is disabled. I want to be able to enable it when any of the text boxes/combo boxes/ check boxes are changed.

有一个容易的方法来做到这一点不增加单个事件处理这些物品?

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

推荐答案

下面是足以让你看呆了。您可能需要添加额外的的foreach 为循环需要其他控制类型。这种做法的好处是,你只需要代码每控制几行类型,而不是每个实例,使用这种方法。

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<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;



修改 addHandlers后方法来支持所有你的控件,并添加所有的控件到窗体后调用它,你可以简单地订阅 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).

这篇关于有火灾事件每当有文本框所做的任何更改,comboboxs等内部形状的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆