c# - C# 如何与两个生成的控件交互?
问题描述
我有一个Checkbox
, 标记后它会创建一个Listbox
,Button
和一个Textbox
. 生成的Button
,应该有用生成的值Click
填充生成 的事件。Listbox
Textbox
但是我在里面得到编译时错误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;
}
解决方案
除了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();
}
推荐阅读
- r - 从表达式字符串保存 RData 和 RDS 文件对象
- arrays - 如何将函数应用于json数组的每个元素?
- django - Django ImportError:模块“social_core.backends.google”未定义“GoogleOpenId”属性/类
- go - 选择性地向特定客户端发送事件
- python - Python - 根据表示列和行位置(坐标)的键将字典中的值写入 .csv
- r - 小册子问题编织参考在部分末尾
- amazon-web-services - 我的 AWS Application Load Balancer 如何获得比请求更多的 503?
- javascript - 动态添加幻灯片到 Reveal.js 幻灯片
- vim - 让 vim 完成 #include 行
- angular - 如何使赛普拉斯别名在测试用例之间工作?