【问题标题】:C# How do I interact with two generated controls? [duplicate]C# 如何与两个生成的控件交互? [复制]
【发布时间】:2020-06-03 11:35:57
【问题描述】:

我有一个Checkbox,标记后它将创建一个ListboxButton 和一个Textbox。 生成的Button 应该有Click 事件以用生成的 Textbox 的值填充生成的 Listbox

但我在public System.Windows.Forms.Button AddNewButton() 中得到编译时错误

名称 Txb 在当前上下文中不存在

名称 lb 在当前上下文中不存在

代码如下:

 private void cbDd_CheckedChanged(object sender, EventArgs e)
    {
        AddNewListBox();
        AddNewTextBox();
        AddNewButton();
    }

    public System.Windows.Forms.ListBox AddNewListBox()
    {
        System.Windows.Forms.ListBox lb = new System.Windows.Forms.ListBox();
        this.Controls.Add(lb);
        lb.Top = 74;
        lb.Left = 500;
        cLeft = cLeft + 1;
        return lb;
    }

    public System.Windows.Forms.TextBox AddNewTextBox()
    {
        System.Windows.Forms.TextBox txb = new System.Windows.Forms.TextBox();
        this.Controls.Add(txb);
        txb.Top = 180;
        txb.Left = 500;
        txb.Text = "item name";
        cLeft = cLeft + 1;
        return txb;
    }

    public System.Windows.Forms.Button AddNewButton()
    {
        System.Windows.Forms.Button btn = new System.Windows.Forms.Button();
        this.Controls.Add(btn);
        btn.Top = 210;
        btn.Left = 500;
        btn.Text = "Add item";
        btn.Click += (s, e) => { if (string.IsNullOrEmpty(txb.Text)) return;
                };
        lb.Items.Add(cbTxb.Text);
        return btn;
    }

【问题讨论】:

  • 您的问题是如何在两种方法之间传递值?尝试使用方法参数和字段。
  • 不,我认为这不起作用,当我生成这些控件并尝试激活我的点击事件时,txb 将不起作用。

标签: c# winforms dynamic controls


【解决方案1】:

除了AddNew(ListBox|TextBox|Button)

public System.Windows.Forms.ListBox AddNewListBox()
{
    return new System.Windows.Forms.ListBox() {
      Location = new Point(500, 74),
      parent   = this, // instead of this.Controls.Add(...)
    };
}

public System.Windows.Forms.TextBox AddNewTextBox()
{
    return new System.Windows.Forms.TextBox() {
      Location = new Point(500, 180), 
      Text     = "item name",
      Parent   = this, 
    }; 
}

public System.Windows.Forms.Button AddNewButton() 
{
    return new System.Windows.Forms.Button() {
      Location = new Point(500, 210),
      Text     = "Add item",  
      Parent   = this,  
    };
}

我建议实现AddNewControls(),其中创建的控件可以交互

private void AddNewControls() {
  var lb  = AddNewListBox();
  var txb = AddNewTextBox();
  var btn = AddNewButton();

  btn.Click += (s, e) => {
    // now btn (button) can use txb (TextBox)
    if (string.IsNullOrEmpty(txb.Text)) 
      return;

    //TODO: put relevant code here
  }   

  cLeft += 3;

  //TODO: check lb and cbTxb.Text
  lb.Items.Add(cbTxb.Text);
}

那么就可以放

private void cbDd_CheckedChanged(object sender, EventArgs e) 
{
    AddNewControls();
}

【讨论】:

    猜你喜欢
    • 2014-08-30
    • 2011-09-17
    • 1970-01-01
    • 2019-02-22
    • 1970-01-01
    • 2012-02-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多