【问题标题】:My winform button spawns checkboxes when pressed, how can I let code run when one is checked?我的winform按钮在按下时会产生复选框,我如何让代码在选中时运行?
【发布时间】:2014-11-08 15:37:15
【问题描述】:
    private void NewNoiseButton_Click(object sender, EventArgs e)
    {
        buttonList.Add(new CheckBox());
        int buttonNumber = buttonList.Count - 1;

        buttonList[buttonNumber].Location = new Point(2, buttonList.Count * 30 - 30);
        allNoisePanel.Controls.Add(buttonList[buttonNumber]);
    }

    private void checkboxIsChecked(CheckBox checkBox)
    {
        //How do I make this code run?
    }

    private void checkboxIsUnchecked(CheckBox checkBox)
    {
        //How do I make this code run?
    }

Whenever the 'NewNoiseButton' is checked, I want the void checkBoxIsChecked to run, but since the buttons are created through code, I found this very difficult to do.

【问题讨论】:

  • 您是想将该事件分配给以编程方式创建的控件还是只是checkboxIsChecked(buttonList.Last())
  • 如果你有按钮来控制复选框,那么你可能不需要按钮。只需点击复选框
  • @Sayse 正确,代码应该创建一个按钮列表。
  • 用户,这不是我在最初评论中所说的,您的代码确实已经创建了一个按钮列表,但是您现在要做什么?将事件分配给新的复选框还是只调用方法?

标签: c# winforms button checkbox


【解决方案1】:

我相信,您可以使用以下方法:

List<CheckBox> buttonList = new List<CheckBox>();
void NewNoiseButton_Click(object sender, EventArgs e) {
    var cb = new CheckBox();
    buttonList.Add(cb);

    cb.Location = new Point(2, buttonList.Count * 30 - 30);
    allNoisePanel.Controls.Add(cb);
    cb.CheckedChanged += cb_CheckedChanged;
}
void cb_CheckedChanged(object sender, EventArgs e) {
    CheckBox cb = sender as CheckBox;
    if(cb.Checked)
        checkboxIsChecked(cb);
    else
        checkboxIsUnchecked(cb);
}
void checkboxIsChecked(CheckBox checkBox) {
    //How do I make this code run?
}
void checkboxIsUnchecked(CheckBox checkBox) {
    //How do I make this code run?
}

【讨论】:

    【解决方案2】:

    你可以试试这个:

    private void NewNoiseButton_Click( object sender, EventArgs e )
    {
      CheckBox checkBox = new CheckBox();
      buttonList.Add( checkBox );
      int buttonNumber = buttonList.Count - 1;
      checkBox.CheckedChanged += new EventHandler( CheckBoxCheckedChanged );
    
      buttonList[ buttonNumber ].Location = new Point( 2, buttonList.Count * 30 - 30 );
      allNoisePanel.Controls.Add( buttonList[ buttonNumber ] );
    }
    
    void CheckBoxCheckedChanged( object sender, EventArgs e )
    {
      CheckBox checkBox = sender as CheckBox;
      if (checkBox!=null)
      {
        if (checkBox.Checked)
        {
          // do something
        }
        else
        {
          // do something else
        }
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-10-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-07
      • 1970-01-01
      相关资源
      最近更新 更多