首页 > 解决方案 > 每次在c#中以编程方式单击按钮时如何添加组合框的新实例

问题描述

我想创建 ac# windows 窗体,如果单击“添加组合框”按钮,系统将在每次单击时创建 1 个“组合框”实例。

每个实例的位置将在彼此下方加上 5px 经度。

如果可能的话,请用一些修复值填充新实例。

标签: c#winformscombobox

解决方案


您可以在单击按钮时执行以下操作(注释在代码中):

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);
}

推荐阅读