winforms中ListView控件基本用法

   1: using System;
   2: using System.Collections.Generic;
   3: using System.ComponentModel;
   4: using System.Data;
   5: using System.Drawing;
   6: using System.Linq;
   7: using System.Text;
   8: using System.Windows.Forms;
   9:  
  10: namespace TestApp
  11: {
  12:     public partial class Form4 : Form
  13:     {
  14:         public Form4()
  15:         {
  16:             InitializeComponent();
  17:         }
  18:  
  19:         private void Form4_Load(object sender, EventArgs e)
  20:         {
  21:             //设置ListView的显示方式
  22:             listView1.View = View.Details;
  23:  
  24:             //设置大图标视图方式对应的imagelist
  25:             listView1.LargeImageList = imageList2;
  26:             //设置小图标视图方式对应的imagelist
  27:             listView1.SmallImageList = imageList1;
  28:  
  29:             //设置显示网格线
  30:             listView1.GridLines = true;
  31:             //设置只可以选择一项
  32:             listView1.MultiSelect = false;
  33:             //整行选中
  34:             listView1.FullRowSelect = true;
  35:  
  36:             //设置表头
  37:             listView1.Columns.Add("信息",150);//名称 宽度
  38:             listView1.Columns.Add("来源",100);
  39:             listView1.Columns.Add("数值");
  40:             
  41:             //添加项
  42:             ListViewItem item = new ListViewItem();
  43:             item.Text = "选项一"; //显示文字
  44:             item.Tag = "001";     //设置tag 用于隐藏信息 比如主键
  45:             item.ImageIndex = 0; //对应在imagelist中图片索引
  46:             listView1.Items.Add(item); //将列表项加入到ListView中
  47:  
  48:             ListViewItem item2 = new ListViewItem();
  49:             item2.Text = "信息2";
  50:             item2.Tag = "002";
  51:             item2.ImageIndex = 3;
  52:             item2.SubItems.AddRange(new string[]{"网络","100"}); //添加子项 
  53:             listView1.Items.Add(item2);
  54:             
  55:         }
  56:  
  57:         private void button1_Click(object sender, EventArgs e)
  58:         {
  59:             if (listView1.SelectedItems.Count > 0)
  60:             {
  61:                 MessageBox.Show(listView1.SelectedItems[0].Text); //获得选择项的第一列的值
  62:                 MessageBox.Show(listView1.SelectedItems[0].Tag.ToString());//获得选择项的tag值
  63:  
  64:                 MessageBox.Show(listView1.SelectedItems[0].SubItems[1].Text);//获得选择项的第二列的值
  65:             }
  66:             else
  67:             {
  68:                 MessageBox.Show("请选择后再单击");
  69:             }
  70:         }
  71:     }
  72: }

外观:

winforms中ListView控件基本用法_第1张图片

你可能感兴趣的:(winforms中ListView控件基本用法)