C#如何与两个生成的控件交互?
我有一个C#如何与两个生成的控件交互?,c#,winforms,dynamic,controls,C#,Winforms,Dynamic,Controls,我有一个复选框,标记后将创建一个列表框、按钮和一个文本框。 生成的按钮应具有单击事件,以使用生成的文本框的值填充生成的列表框 但是我在public System.Windows.Forms.Button AddNewButton()中得到了编译时错误: 当前上下文中不存在Txb NOT名称 当前上下文中不存在名称lb NOT 代码如下: private void cbDd_CheckedChanged(object sender, EventArgs e) { AddN
复选框
,标记后将创建一个列表框
、按钮
和一个文本框
。
生成的按钮
应具有单击
事件,以使用生成的文本框的值填充生成的列表框
但是我在public System.Windows.Forms.Button AddNewButton()中得到了编译时错误:
当前上下文中不存在Txb NOT名称
当前上下文中不存在名称lb NOT
代码如下:
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;
}
除了AddNew
(ListBox | TextBox |按钮
)
我建议在创建的控件可以相互交互的地方实施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();
}
您的问题是如何在两种方法之间传递值?尝试使用方法参数和字段。不,我认为这不起作用,当我生成这些控件并尝试激活单击事件时,txb将不起作用。
private void cbDd_CheckedChanged(object sender, EventArgs e)
{
AddNewControls();
}