CheckBox控件
常用属性:Text、Name、Checked、CheckState、ThreeState
常用事件:CheckedChanged、CheckStateChanged
知识点1:
Checked:表示控件是否选中
CheckState:表示控件选中的状态,有三种状态,分别是:checked,unchecked,indeterminate
而且CheckState要和ThreeState属性组合使用
ThreeState属性控制CheckBox显示三种状态还是两种状态。
CheckBox的三种状态如下:
知识点2:
heckedChanged和CheckStateChanged事件功能基本相同,但是heckedChanged相比CheckStateChanged先发生;
知识点3:
CheckBox分组使用时,最好放入panel组件中使用,方便按组遍历;
实现如下功能:
public partial class FormCheckBox : Form { public FormCheckBox() { InitializeComponent(); this.Load += FormCheckBox_Load; } //分别对每组CheckBox注册CheckedChanged事件 private void FormCheckBox_Load(object sender, EventArgs e) { foreach (Control item in panelIntresting.Controls) { ((CheckBox)item).CheckedChanged += FormCheckBox_CheckedChanged; } foreach (Control item in panelRoles.Controls) { ((CheckBox)item).CheckedChanged += FormCheckBox_CheckedChanged1; } } List<string> listIntresting = new List<string>(); List<string> listRols = new List<string>(); private void FormCheckBox_CheckedChanged1(object sender, EventArgs e) { CheckBox c = sender as CheckBox; if (c.Checked) { listRols.Add(c.Text); } else { listRols.Remove(c.Text); } } private void FormCheckBox_CheckedChanged(object sender, EventArgs e) { CheckBox c = sender as CheckBox; if (c.Checked) { listIntresting.Add(c.Text); } else { listIntresting.Remove(c.Text); } } private void btnSubmit_Click(object sender, EventArgs e) { string strState = cbNomal.Checked ? "正常": "不正常"; string strIntresting = string.Join(",", listIntresting); string strRols = string.Join(",", listRols); MessageBox.Show($"状态:{strState};兴趣:{strIntresting};角色:{strRols};"); } } }