如果Winform里有100个label,分别是:
label1
label2
label3
......
label100
而comboBox1的选项里有那些label的Name,请问如何选中comboBox1中的label名称,单击“删除”按钮将指定的label删除。如何做?

解决方案 »

  1.   

    从那些Label的容器中把选中的Label去处掉。假设Container为Label的容器
    Container.Controls.remove(控件);
      

  2.   

    this.Controls.Remove(comboBox1.Text);   不行
    this.Conrols.remove(控件id); 不能实现自由选择~
      

  3.   

    1、通过comboBox1.Text确定选中的lable控件的id:lbId,
    然后调用this.Controls.remove(lbId);删除控件
      

  4.   

    int ii = 1, xx = 10, yy = 10;
     private void button1_Click(object sender, EventArgs e)
            {
                ii++;
                yy = yy + 50;
                System.Windows.Forms.Label la = new Label();
                la.Name = "labela" + ii.ToString();
                la.AutoSize = true;
                la.Text = "好友名字 "+ii;            
                la.Left = xx;
                la.Top = yy;
                comboBox1.Items.Add(la.Name);   
                this.Controls.Add(la);       
            }
      private void button2_Click(object sender, EventArgs e)
            {
              this.Controls.Remove(comboBox1.Text);           
             }
    这样写不行啊~..
      

  5.   

    以上代码提示错误:
    1、错误 1 与“System.Windows.Forms.Control.ControlCollection.Remove(System.Windows.Forms.Control)”最匹配的重载方法具有一些无效参数
    2、错误 2 参数“1”: 无法从“string”转换为“System.Windows.Forms.Control”
      

  6.   

    private System.Windows.Forms.Button btnAdd;        // 添加
    private System.Windows.Forms.ComboBox comboBox1;   // comboBox
    private System.Windows.Forms.Button btnRmv;        // 移除
    private System.Windows.Forms.GroupBox labGrp;      // 控件容器// 事件处理
    /// <summary>
    /// 添加。
    /// </summary>
    private void btnAdd_Click(object sender, System.EventArgs e)
    {
        int num = labGrp.Controls.Count;    Label lbl = new Label();
        lbl.Text = "friend " + (num + 1);
        int left = 10, top = 20;
        if(labGrp.Controls.Count > 0)
        {
    Control lastCtrl = labGrp.Controls[labGrp.Controls.Count - 1];
    top = lastCtrl.Top + lastCtrl.Height;
        }
        lbl.Location = new Point(left, top);
        comboBox1.Items.Add(lbl.Text);
        labGrp.Controls.Add(lbl);
    }/// <summary>
    /// 移除。
    /// </summary>
    private void btnRmv_Click(object sender, System.EventArgs e)
    {
        int selectedIndex = comboBox1.SelectedIndex;
        if(selectedIndex >= 0)
        {
    labGrp.Controls.RemoveAt(selectedIndex);
    comboBox1.Items.RemoveAt(selectedIndex);
    this.RelocateLabels(selectedIndex);
        }
    }/// <summary>
    /// 重新排列剩余的 Label。
    /// </summary>
    /// <param name="removedIndex">被移除的 Label 的索引。</param>
    private void RelocateLabels(int removedIndex)
    {
        for(int i = 0;i < labGrp.Controls.Count;i++)
        {
    if(i >= removedIndex)
    {
    labGrp.Controls[i].Top -= labGrp.Controls[i].Height;
    }
        }
    }