using System;
using System.Windows.Forms;
namespace CheckedListBoxExample
{
public class Form1 : Form
{
private CheckedListBox checkedListBox1;
private Button button1;
private Label label1;
public Form1()
{
// 初始化控件
checkedListBox1 = new CheckedListBox();
button1 = new Button();
label1 = new Label();
// 设置控件属性
checkedListBox1.Items.AddRange(new object[] { "Item 1", "Item 2", "Item 3", "Item 4" });
checkedListBox1.Location = new System.Drawing.Point(12, 12);
checkedListBox1.Size = new System.Drawing.Size(150, 94);
button1.Text = "Show Selected";
button1.Location = new System.Drawing.Point(12, 112);
button1.Click += new EventHandler(button1_Click);
label1.Location = new System.Drawing.Point(12, 140);
label1.Size = new System.Drawing.Size(260, 80);
// 将控件添加到窗体
this.Controls.Add(checkedListBox1);
this.Controls.Add(button1);
this.Controls.Add(label1);
// 设置窗体属性
this.Text = "CheckedListBox Example";
this.Size = new System.Drawing.Size(300, 250);
}
private void button1_Click(object sender, EventArgs e)
{
// 获取选中的项并显示在标签上
string selectedItems = "Selected Items: ";
for (int i = 0; i < checkedListBox1.CheckedItems.Count; i++)
{
selectedItems += checkedListBox1.CheckedItems[i].ToString() + ", ";
}
if (selectedItems.EndsWith(", "))
{
selectedItems = selectedItems.Substring(0, selectedItems.Length - 2);
}
label1.Text = selectedItems;
}
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.Run(new Form1());
}
}
}
创建窗体和控件:
Form1
类继承自 Form
,并在构造函数中初始化了 CheckedListBox
、Button
和 Label
控件。设置控件属性:
checkedListBox1
添加了四个项目("Item 1" 到 "Item 4"),并设置了其位置和大小。button1
设置了按钮的文本为 "Show Selected",并绑定了点击事件处理程序 button1_Click
。label1
用于显示选中的项,并设置了其位置和大小。事件处理:
button1_Click
方法获取 checkedListBox1
中所有选中的项,并将它们以字符串的形式拼接起来,最后显示在 label1
上。启动应用程序:
Main
方法是应用程序的入口点,调用 Application.Run
启动窗体。这个示例展示了如何使用 CheckedListBox
控件来选择多个项,并通过按钮点击事件显示选中的项。
上一篇:c# crc16校验
下一篇:c#控件
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站