c# listview

wisdomone1發表於2012-02-27

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace installfirstproject
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            //labeledit指標子項標籤是否可以編輯
            listView1.LabelEdit = true;
            listView1.Items.Add("a");
            listView1.Items.Add("b");
        }
        //新增子項
        private void button1_Click(object sender, EventArgs e)
        {
            if (textBox1.Text =="")
            {
                MessageBox.Show("要新增到LISTVIEW的項為空");
            }
            else
            {
                listView1.Items.Add(textBox1.Text.Trim());
                //listview各個子項的顯示方式,經測試僅為list;每個項左邊才會完整顯示checkbox核取方塊
               
                //經測試如果子項顯示方式為list且子項左側為核取方塊時,button2_click選中子項進行刪除某子項不起作用,註解掉對比測試下
                //listView1.View = View.List;
                //listView1.CheckBoxes = true;
                try
                {
                    //判斷子項個數
                    if (listView1.Items.Count < 2)
                    {
                        listView1.Items.Add("給力");
                    }
                    else
                    {
                        //selected指標是否選中某個子項
                        listView1.Items[2].Selected = true;
                    }
                }
                catch(Exception ec)
                {
                    MessageBox.Show(ec.Message);
                }
                textBox1.Clear();
               

            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            //刪除前判斷是否有子項,否則刪除會報異常;在listview中,類似於資源管理器右視窗
            if (listView1.Items.Count == 0)
            {
                MessageBox.Show("不用刪除,沒有子項");
                return;
            }
            //else if (listView1.SelectedItems.Count == 0)
            //{
            //    MessageBox.Show("有子項,但當前沒有選中子項");

            //}
            else
            {
                //選中了子項
               
                //經測試selecteditems.clear方法失效
               // listView1.SelectedItems.Clear();
               // MessageBox.Show("已成功刪除子項"+listView1.SelectedItems[listView1.SelectedItems[0].Index]);
                //移除所有子項
                //listView1.Items.Clear();

                //下列方法是取消選擇吧
                listView1.SelectedItems.Clear();

                //remove為刪除指定子項,方法引數listviewitem
               // listView1.Items.Remove();
                listView1.Items.RemoveAt(0);
                //int index = listView1.SelectedItems.IndexOf(listView1.SelectedItems);
            }
        }
      
    }
}

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/9240380/viewspace-717257/,如需轉載,請註明出處,否則將追究法律責任。

相關文章