C# CheckedListBox控件的用法总结
C# CheckedListBox控件的用法总结
简介
C# CheckedListBox控件是Windows窗体应用程序中常用的控件之一,它可以让用户在一个列表中,通过勾选方式选择其中的多个选项。本文将总结C# CheckedListBox控件的用法,包括如何进行添加、删除、修改、选中等操作,以及如何获取用户选择的内容。
创建CheckListBox控件
在Windows窗体应用程序中,可以通过如下代码创建一个新的CheckedListBox控件。
private CheckedListBox checkedListBox1;private void Form1_Load(object sender, EventArgs e){ checkedListBox1 = new CheckedListBox(); checkedListBox1.Location = new Point(10, 10); checkedListBox1.Height = this.ClientSize.Height -20; checkedListBox1.Width = this.ClientSize.Width -20; this.Controls.Add(checkedListBox1);}这里创建了一个CheckListBox控件,并设置了它的位置和大小,并将其添加到了当前窗体中。
添加和删除项
可以通过Items属性来添加和删除CheckListBox控件中的项,如下所示:
private void AddItem(string itemName){ checkedListBox1.Items.Add(itemName);}private void RemoveItem(string itemName){ checkedListBox1.Items.Remove(itemName);}这里AddItem方法可以添加一个名为itemName的项,而RemoveItem方法可以删除一个名为itemName的项。
修改和获取项
可以通过Items属性获取CheckListBox控件中的项,并进行修改,如下所示:
private void ModifyItem(string itemName, int index){ checkedListBox1.Items[index] = itemName;}private string GetItem(int index){ return checkedListBox1.Items[index].ToString();}这里ModifyItem方法可以将CheckListBox控件的第index项修改为名为itemName的项,而GetItem方法可以获取控件中第index项的名称。
选中和取消选中项
可以通过SetItemChecked方法来实现CheckListBox控件中项的选中和取消选中,如下所示:
private void CheckItem(int index){ checkedListBox1.SetItemChecked(index, true);}private void UncheckItem(int index){ checkedListBox1.SetItemChecked(index, false);}这里CheckItem方法将CheckListBox控件的第index项勾选,而UncheckItem方法将第index项取消勾选。
获取用户选择的内容
可以通过CheckedItems属性来获取用户选择的内容,如下所示:
private string GetCheckedItems(){ string result = ""; foreach (string item in checkedListBox1.CheckedItems) { result += item + ","; } return result.TrimEnd(',');}这里GetCheckedItems方法将返回用户选择的项的名称,多个项之间用逗号隔开。其中,CheckedItems属性返回CheckListBox控件中已被勾选的项。
示例说明
示例1:添加项,选中项,获取已选项
private void button1_Click(object sender, EventArgs e){ // 添加3个项 AddItem("A"); AddItem("B"); AddItem("C"); // 选中第一个和第三个项 CheckItem(0); CheckItem(2); // 获取已选项 string checkedItems = GetCheckedItems(); MessageBox.Show(checkedItems); // 显示"A,C"}这里创建了一个包含三个项的CheckListBox控件,选中了第一个和第三个项,并获取了已选项,最终弹出消息框显示"A,C"。
示例2:删除项,修改项,取消选中项
private void button2_Click(object sender, EventArgs e){ // 删除第二个项 RemoveItem("B"); // 将第一个项修改为"D" ModifyItem("D", 0); // 取消选中第三个项 UncheckItem(2);}这里删除了第二个项,将第一个项的名称修改为"D",并取消选中了第三个项。
结论
本文总结了C# CheckedListBox控件的用法,包括创建控件、添加、删除、修改、选中、获取已选项等操作,并给出了两条示例说明。希望对读者有所帮助。