c#如何遍历复选框列表并找到已选中和未选中的内容
作者:野牛程序员:2024-01-07 19:17:35C#阅读 2920
使用 C# 遍历复选框列表并找到已选中和未选中的内容可以通过以下方式实现:
foreach (Control control in yourCheckBoxList.Controls)
{
if (control is CheckBox checkBox)
{
// 检查复选框是否被选中
if (checkBox.Checked)
{
// 处理已选中的复选框
// 可以输出或者进行其他操作
}
else
{
// 处理未选中的复选框
// 可以输出或者进行其他操作
}
}
}下面是一个简单的 C# 示例代码,演示如何遍历复选框列表并找到已选中和未选中的内容。
using System;
using System.Windows.Forms;
namespace CheckBoxListExample
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
// 在窗体加载时添加一些复选框到 Panel 中
for (int i = 1; i <= 5; i++)
{
CheckBox checkBox = new CheckBox();
checkBox.Text = "CheckBox " + i;
checkBox.Checked = i % 2 == 0; // 设置偶数复选框为已选中状态
panel1.Controls.Add(checkBox);
}
}
private void button1_Click(object sender, EventArgs e)
{
// 遍历复选框列表并找到已选中和未选中的内容
foreach (Control control in panel1.Controls)
{
if (control is CheckBox checkBox)
{
if (checkBox.Checked)
{
Console.WriteLine("已选中: " + checkBox.Text);
}
else
{
Console.WriteLine("未选中: " + checkBox.Text);
}
}
}
}
}
}野牛程序员教少儿编程与信息学奥赛-微信|电话:15892516892

