C# ListBox中添加CheckBox并遍历添加的CheckBox

在使用ListBox时,有时需要动态的添加CheckBox,并在添加后根据CheckBox的选中情况执行相应的事件。
首先是添加的代码:

DirectoryInfo TheFolder = new DirectoryInfo("G:/proj/ActiveDemoEarth/WindowsFormsApplication1/bin/x64/Release/line/");
            //遍历文件
            int x1 = this.listBox1.Location.X;
            int y1 = 10;

            int y2 = 10;

            int y3 = 10;
            CheckBox checkbox = new CheckBox();
            checkbox.Font = new System.Drawing.Font("宋体", 10F);
            checkbox.Location = new Point(x1 + 30, y1);
            y1 += 30;
            checkbox.Name = NextFile.Name;
           checkbox.Text = "无人机" + uav_nums.ToString();
           uav_nums += 1;
           this.listBox1.Controls.Add(checkbox);

遍历添加后的CheckBox的代码:

 foreach(var control in listBox1.Controls)
                {
                    CheckBox checkbox = (CheckBox)control;
                    checkbox.CheckState = CheckState.Checked;
                }

你可能感兴趣的:(C#)