ListView中加复选框并实现全选(全不选)

using System;
using System.Windows.Forms;
using System.IO;
namespace 带复选框的ListView
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            this.Load += new EventHandler(Form1_Load);
            this.button1.Click += new EventHandler(Button_Click);
            this.button2.Click += new EventHandler(Button_Click);
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            listView1.CheckBoxes = true;
            listView1.View = View.Details;
            listView1.GridLines = true;
            listView1.Columns.Add("文件名称", 150, HorizontalAlignment.Left);
            listView1.Columns.Add("创建时间", 200, HorizontalAlignment.Left);

            DirectoryInfo di=new DirectoryInfo(@"D:\");
            foreach (FileInfo fi in di.GetFiles())
            {
                ListViewItem lv = new ListViewItem();
                lv.Text = fi.Name;
                lv.SubItems.Add(fi.CreationTime.ToString());
                listView1.Items.Add(lv);
            }
        }

        private void Button_Click(object sender, EventArgs e)
        {
            Button b = (Button)sender;
            if (b.Text == "全选")
            {
                foreach (ListViewItem item in listView1.Items)
                {
                    item.Checked = true;
                }
            }
            else if (b.Text == "清空")
            {
                foreach (ListViewItem item in listView1.Items)
                {
                    item.Checked = false;
                }
            }
        }
    }
}

你可能感兴趣的:(C#,c#学习笔记)