c# - 如何将按钮从子窗体动态添加到主窗体
问题描述
当我选择了位于另一个表单Button
上的项目时,我想在我的主表单上添加一个功能。ListView
下面的代码我已经放在ListView
表单上,但我不确定我做对了,因为当项目被选中时没有任何反应。
Point newLoc = new Point(5,5);
Button b = new Button();
b.Size = new Size(10, 50);
b.Location = newLoc;
newLoc.Offset(0, b.Height + 5);
Controls.Add(b);
解决方案
首先,您必须找到主表单(假设您正在使用WinForms):
using System.Linq;
...
//TODO: Put the right type instead of MyMainForm
MyMainForm mainForm = Application
.OpenForms
.OfType<MyMainForm>()
.LastOrDefault(); // If there many opened main forms, let's use the last one
然后如果找到表单,让我们添加一个按钮:
public partial class MyChildForm : Form {
// It seems it should be a field to store the next button position
private Point newLoc = new Point(5, 5);
private Button addButtonToMainForm() {
//TODO: Put the right type instead of MyMainForm
MyMainForm mainForm = Application
.OpenForms
.OfType<MyMainForm>()
.LastOrDefault();
// If Main Form has been found, let's add a button on it
if (mainForm != null) {
Button b = new Button() {
Size = new Size(10, 50),
Location = newLoc,
Parent = mainForm, // Place the button on mainForm
}
newLoc.Offset(0, b.Height + 5);
return b;
}
return null;
}
private void myListView_ItemSelectionChanged(object sender,
ListViewItemSelectionChangedEventArgs e) {
// If item selected (not unselected)
if (e.Item.Selected) {
//TODO: Some other conditions which on the item that has been selected
// Button on the Main Form, null if it hasn;t been created
Button createdButton = addButtonToMainForm();
}
}
...
推荐阅读
- r - 月到整数 R
- php - 获取数组值并以空格分隔显示为类名(Jquery)
- r - 交互式 geom_bar 中的条形切换位置
- sql - 如何在计算另一列 SQL Server 的情况下获取“END”别名
- c# - 从并发字典c#中获取随机元素
- mysql - 使用 MySQL 在每个组中运行总计
- c# - 我如何知道我的 HTTP 端口请求是否在 c# 中有效?
- web-services - 调用 init 方法失败;嵌套异常是 java.lang.VerifyError: JVMCFRE004 unknown bytecode;班级
- c# - 页面在 Server.Transfer() 之后触发 page_load
- java - 可执行的 jar 文件窗口大小更大,不如通过 netbeans 打开时那么清晰