Summary of usage of C#'s CheckedListBox control
CheckedListBox is one of the commonly used controls in C# Windows Forms. It is used to display a set of optional options, and the user can check the Marquee selects one or more options. In this article, we will summarize the usage of the CheckedListBox control and provide some specific code examples.
1. Basic usage of CheckedListBox
CheckedListBox checkedListBox1 = new CheckedListBox();
checkedListBox1.Items.Add("选项1"); checkedListBox1.Items.Add("选项2"); checkedListBox1.Items.Add("选项3");
// 获取选中项的索引 for (int i = 0; i < checkedListBox1.CheckedIndices.Count; i++) { int selectedIndex = checkedListBox1.CheckedIndices[i]; } // 获取选中项的值 foreach (var item in checkedListBox1.CheckedItems) { string selectedValue = item.ToString(); }
checkedListBox1.CheckedChanged += CheckedListBox1_CheckedChanged; private void CheckedListBox1_CheckedChanged(object sender, EventArgs e) { // 处理选项改变的逻辑 }
2. Advanced usage of CheckedListBox
checkedListBox1.SetItemChecked(0, true); // 默认选中第一个选项
List<string> dataList = new List<string> { "选项1", "选项2", "选项3" }; checkedListBox1.DataSource = dataList;
checkedListBox1.ItemCheck += CheckedListBox1_ItemCheck; private void CheckedListBox1_ItemCheck(object sender, ItemCheckEventArgs e) { // 修改选项样式 if (e.NewValue == CheckState.Checked) { checkedListBox1.SetItemChecked(e.Index, true); checkedListBox1.SetItemCheckState(e.Index, CheckState.Indeterminate); } }
checkedListBox1.CheckOnClick = true;
Summary:
The above are the basic usage and some advanced usage of the CheckedListBox control. By using the CheckedListBox control, you can easily implement the multi-selection function and customize it according to actual needs. I hope this article can help you better understand and use the CheckedListBox control.
The above is the detailed content of Summary of how to use the CheckedListBox control in C#. For more information, please follow other related articles on the PHP Chinese website!