Panel容器的作用,可以呈放其他控件的容器
属性:Anchor,Dock
知识点1:
实现如下功能,学习动态添加控件和遍历控件的方法。
代码:
using System; using System.Collections.Generic; using System.Drawing; using System.Windows.Forms; namespace ControlsTest { public partial class FormPanel : Form { public FormPanel() { InitializeComponent(); this.Load += FormPanel_Load; } private void FormPanel_Load(object sender, EventArgs e) { panel4.Controls.Clear(); for (int i = 0; i < 7; i++) { CheckBox cb = new CheckBox(); cb.Text = "选项" + i.ToString(); cb.Size = new Size(60, 20);//见注意 cb.Location = new Point(60 * i + 5, 5); panel4.Controls.Add(cb); } for (int i = 0; i < 7; i++) { RadioButton rb = new RadioButton(); rb.Text = "单选" + i; rb.Size = new Size(60, 20); rb.Location = new Point(60 * i + 5, 30); panel4.Controls.Add(rb); } } private void button1_Click(object sender, EventArgs e) { List<string> list = new List<string>(); string str = ""; foreach (var item in panel4.Controls) { if (item is CheckBox) { CheckBox cb = item as CheckBox; if (cb.Checked) { list.Add(cb.Text); } } if (item is RadioButton) { RadioButton rb = item as RadioButton; if (rb.Checked) { list.Add((string)rb.Text); } } } str = String.Join(";", list); MessageBox.Show(str); } } }
注意,动态添加控件时需要设置控件的大小,防止控件遮挡影响显示。
标签:容器,CheckBox,控件,cb,item,rb,new,Panel From: https://www.cnblogs.com/hanzq/p/16808744.html