c#

C# CheckedListBox控件的用法

小云
122
2023-09-14 03:50:42
栏目: 编程语言

C# CheckedListBox控件用于在Windows窗体应用程序中显示一个带有复选框的列表。用户可以选择或取消选择列表中的项目。

以下是C# CheckedListBox控件的基本用法示例:

  1. 在窗体上拖放一个CheckedListBox控件。

  2. 设置CheckedListBox控件的属性:

  1. 在代码中处理CheckListBox控件的事件:

下面是一个示例代码,演示如何使用CheckedListBox控件:

using System;
using System.Windows.Forms;
namespace CheckedListBoxExample
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
// 添加项目到CheckedListBox控件
checkedListBox1.Items.Add("Item 1");
checkedListBox1.Items.Add("Item 2");
checkedListBox1.Items.Add("Item 3");
checkedListBox1.Items.Add("Item 4");
}
private void checkedListBox1_ItemCheck(object sender, ItemCheckEventArgs e)
{
// 获取当前项目的选择状态
string item = checkedListBox1.Items[e.Index].ToString();
CheckState state = e.NewValue;
// 在控制台打印选择状态
Console.WriteLine(item + " - " + state.ToString());
}
private void checkedListBox1_SelectedIndexChanged(object sender, EventArgs e)
{
// 获取选中的项目
string selectedItem = checkedListBox1.SelectedItem.ToString();
// 在MessageBox中显示选中的项目
MessageBox.Show(selectedItem + " selected");
}
}
}

在上面的示例中,在窗体加载时添加了四个项目到CheckedListBox控件。然后,处理了ItemCheck事件和SelectedIndexChanged事件,以演示如何获取项目的选择状态和选中的项目。

0
看了该问题的人还看了