效果描述:
实现勾选全部选项自动把全选按钮勾上;选项中有一个没有勾选,全选按钮则不勾选
private int chFlag = 1;//记录是否触发全选事件 //设置全选按钮状态 private void SetCheckState() { string flag = ""; for (int i = 0; i < lvUser.Items.Count; i++) { flag += lvUser.Items[i].Checked.ToString().ToLower(); } if (!flag.Contains("true")) { chFlag = 2; cbAll.Checked = false; chFlag = 1; } if (!flag.Contains("false")) { chFlag = 1; cbAll.Checked = true; } if (flag.Contains("true") && flag.Contains("false")) { chFlag = 2; cbAll.Checked = false; chFlag = 1; } } //列表选中事件 private void lvUser_ItemChecked(object sender, ItemCheckedEventArgs e) { chFlag = 1; SetCheckState(); } //全选按钮事件 private void cbAll_CheckedChanged(object sender, EventArgs e) { if (chFlag != 2) { if (lvUser.Items.Count > 0) { if (cbAll.Checked) { foreach (ListViewItem item in lvUser.Items) { item.Checked = true; } } else { foreach (ListViewItem item in lvUser.Items) { item.Checked = false; } } } } }