【问题标题】:Adding event handlers Dynamically to controls within a panel将事件处理程序动态添加到面板中的控件
【发布时间】:2013-05-02 17:43:25
【问题描述】:

简而言之,我有一堂课:

class MyPanel
{
    Panel p_panel;                     //declaring all the elements I need
    CheckBox cb_choice;
    RadioButton rb_nagy, rb_kicsi;
    TextBox tb_db;

    public Panel getPanel() {        
        create();                     //creating all the elements I need, then putting them all in the created Panel.
        customize();                  //setting the panel's size, and the other control's locations within the panel.
        return p_panel;               //so if I call this method from an other class, this method will return a panel with all the controls inside.

在另一个类中,我有一个面板列表,所有这些面板都是使用上述方法创建的。 布局已经完成,它工作得很整齐,我可以在屏幕上添加任意数量的内容。但现在我想为这些控件添加一些功能。例如,除非启用复选框,否则我希望禁用所有单选按钮。 那么如何将检查更改事件添加到面板列表中的所有复选框?

【问题讨论】:

  • 在复选框的事件处理程序中(值已更改或其他),您可以执行此伪代码if enabled, disable radio buttons 吗?是这个意思吗?
  • 我需要在面板列表的每个单独成员中动态执行此操作的代码。
  • 您的问题描述有点含糊,我无法真正回答这个问题——我不确定您希望每个复选框如何专门与单选按钮交互......但事件连接到每个复选框应该可以解决问题。我不会只给你代码,你必须先尝试一下。
  • 不是动态创建界面,而是在您的项目中添加一个 UserControl 并在设计时将所有这些控件放置在上面。然后你可以向 UserControl 添加代码......为什么要这样做?

标签: c# events dynamic panel handler


【解决方案1】:

您似乎只是想知道如何将EventHandlers 动态添加到您的控件中!?

可以这样做:

cb_choice.CheckedChanged += cb_choice_CheckedChanged;

或者如果你想更明确(两种方式都一样)。

cb_choice.CheckedChanged += new EventHandler(cb_choice_CheckedChanged);

并定义一个处理方法:

private void cb_choice_CheckedChanged(object o, EventArgs args)
{
    //add code to enable/disable radiobuttons
}

【讨论】:

    猜你喜欢
    • 2011-10-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多