需求效果
如上图操作添加按钮,则下面自动增加一行GROUPBOX控件,操作删除则自动删除最后一行开始的BROUPBOX控件.
实现步骤
1)定义一个记录行数的全局变量
1
| public int watch_num = 0;
|
2)编写动态添加的代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
| private void addWatchFrom(int _series,string _diskName) { try { GroupBox s1 = new GroupBox(); s1.Top = 200 + _series*90; s1.Left = 8; s1.Width = 260; s1.Height = 80; this.Controls.Add(s1); } catch (Exception ex) { MessageBox.Show(ex.Message); } } private void button3_Click(object sender, EventArgs e) { addWatchFrom(watch_num, "C"); watch_num++; }
|
3)编写删除按钮的操作
这儿需要先遍历所有添加的GroupBOX控件,然后依据其纵向Y轴的变化,定位到需要删除的控件,实现删除。注意控件编号要减一,否则会异常。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
| private void button4_Click(object sender, EventArgs e) { if ((this.watch_num-1) >=0) { foreach (Control obj0 in this.Controls ) { if (obj0.GetType().ToString().Equals("System.Windows.Forms.GroupBox")) { if (obj0.Location.Y ==(200 + (this.watch_num-1) * 90)) { this.Controls.Remove(obj0); if (this.watch_num > 0) { this.watch_num--; } break; } } } } }
|
相关链接(侵删)
- C#实现动态添加和删除控件
=================我是分割线=================
欢迎到公众号来唠嗑: