Charlie Calvert on Elvenware

Writing Code and Prose on Computers

Elvenware

Learn ListViews

Here is a simple example of how to use a ListView. Note the reusable SetUpColumns method.

using System;
using System.Windows.Forms;

namespace LearnListViews
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            buttonInsertData.Enabled = false;
        }

        private void buttonListViews_Click(object sender, EventArgs e)
        {
            SetUpColumns(listView1, 
            	"One", "Two", "Three", "Four", "Five");
            buttonInsertData.Enabled = true;
        }

        public void SetUpColumns(ListView listView, 
        	params string[] columns)
        {
            listView.View = View.Details;
            listView.GridLines = true;

            foreach (var column in columns)
            {
                listView.Columns.Add(column);
            }
        }

        private void buttonInsertData_Click(object sender, EventArgs e)
        {
            string[] list = new string[] 
            { 
            	"Able", 
            	"Baker", 
            	"Charlie", 
            	"Delta", 
            	"Echo" 
            }; 
            ListViewItem lvi = new ListViewItem(list);
            listView1.Items.Add(lvi);
        }
    }
}