c# - 每次在c#中以编程方式单击按钮时如何添加组合框的新实例
问题描述
我想创建 ac# windows 窗体,如果单击“添加组合框”按钮,系统将在每次单击时创建 1 个“组合框”实例。
每个实例的位置将在彼此下方加上 5px 经度。
如果可能的话,请用一些修复值填充新实例。
解决方案
您可以在单击按钮时执行以下操作(注释在代码中):
private void button1_Click(object sender, EventArgs e)
{
//create new combo
ComboBox cbo = new ComboBox();
//fill it with values
cbo.Items.Add("value1");
cbo.Items.Add("value2");
//set left location
cbo.Left = 10;
//set default top location
int top = 5;
//if this form contains more then 0 combo boxes, get last combo box Top value and increase it with 5.
if (this.Controls.OfType<ComboBox>().Count() > 0)
top = this.Controls.OfType<ComboBox>().Last().Top + 5;
//set top value to new combo
cbo.Top = top;
//add it to forms control collection
this.Controls.Add(cbo);
}
推荐阅读
- javascript - 使用 window.open 打开外部源时不加载资产文件
- python - 在 Matplotlib 中以上标或下标编写单位的最佳做法是什么?
- azure-devops - 在 Azure DevOps 中,如何查询未完成并延续到当前 sprint 迭代的用户故事?
- javascript - 如何链接我的承诺 - 获取不返回所需的结果
- python - 无法连接到 Chinook.sqlite 数据库
- javascript - 数组字段上的Mongodb E11000重复键错误
- date - 对包含时区的日期范围内的值求和
- ajax - 查找通过 AJAX 加载的 URL
- javascript - 如何清除if语句中的间隔
- visual-studio-code - vscode live 服务器端口设置不起作用,总是在 localhost:8081 中打开