如果Winform里有100个label,分别是:
label1
label2
label3
......
label100
而comboBox1的选项里有那些label的Name,请问如何选中comboBox1中的label名称,单击“删除”按钮将指定的label删除。如何做?
label1
label2
label3
......
label100
而comboBox1的选项里有那些label的Name,请问如何选中comboBox1中的label名称,单击“删除”按钮将指定的label删除。如何做?
Container.Controls.remove(控件);
this.Conrols.remove(控件id); 不能实现自由选择~
然后调用this.Controls.remove(lbId);删除控件
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);
}
这样写不行啊~..
1、错误 1 与“System.Windows.Forms.Control.ControlCollection.Remove(System.Windows.Forms.Control)”最匹配的重载方法具有一些无效参数
2、错误 2 参数“1”: 无法从“string”转换为“System.Windows.Forms.Control”
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;
}
}
}