获取动态创建的控件(组合框)的值

时间:2013-04-30 07:19:37

标签: c# winforms dynamic controls

我有面板,默认情况下是两个组合框和一个“+”按钮,在第一个框架下方创建两个新的组合框,我可以用两个组合框创建多个(n)行,一切正常,我只是无法弄清楚如何获得这些盒子的价值?

以下是创建(添加)控件的代码

private void btnCreateFilter_Click(object sender, EventArgs e)
{

    y += comboBoxHeight;
    ComboBox cb = new ComboBox();
    cb.Location = new Point(x, y);
    cb.Size = new Size(121, 21);

    panelFiltri.Controls.Add(cb);

    yDrugi += comboBoxHeight;
    ComboBox cbSql = new ComboBox();
    cbSql.Location = new Point(xDrugi, yDrugi);
    cbSql.Size = new Size(121, 21);
    panelFiltri.Controls.Add(cbSql);

    btnCancel.Location = new Point(btnCancel.Location.X, btnCancel.Location.Y + 25);
    btnSaveFilter.Location = new Point(btnSaveFilter.Location.X, btnSaveFilter.Location.Y + 25);
} 

这是我失去的代码:

 private void btnSaveFilter_Click(object sender, EventArgs e)
{
    int i;
    foreach (Control s in panelFiltri.Controls)
    {

       //GOT LOST

    }
}

2 个答案:

答案 0 :(得分:1)

您可以将ComboBox中的文本作为

private void btnSaveFilter_Click(object sender, EventArgs e)
{
    foreach (Control control in panelFiltri.Controls)
    {
        if (control is ComboBox)
        {
            string valueInComboBox = control.Text;
            // Do something with this value
        }
    }
}

答案 1 :(得分:0)

我真的不知道你想要实现的目标......也许这会帮助你......

private void btnSaveFilter_Click(object sender, EventArgs e)
{
  foreach (ComboBox comboBox in panelFiltri.Controls)
  {  
     var itemCollection = comboBox.Items;
     int itemCount = itemCollection.Count; // which is 0 in your case
  }
}