We will populate a ListView with a Hashtable. We also handle ItemSelection events for our ListView.
Let's go.
1. Create Empty Project
- Open up Visual Studio and proceed over to File --> New Project
- A new dialog popus up like this:
- Give our empty project a name and click OK. An empty project will get generated for us.
2. Make project a Windows Project
Just right click on your project choose properties and set output type to Windows Application:
3.Program.cs
using System;
using System.Collections;
using System.Drawing;
using System.Windows.Forms;
namespace ListViewHashtable
{
static class Program
{
private static ListView myListView;
public static void Main()
{
setupListView();
populateData();
createMetroForm();
}
private static void createMetroForm()
{
Form myForm = new Form
{
Text = "WinForms ListView : Hashtable - //camposha.info",
ClientSize = new Size(564, 520),
BackColor = Color.Sienna
};
myForm.Controls.Add(myListView);
Application.EnableVisualStyles();
Application.Run(myForm);
}
private static void setupListView()
{
myListView = new ListView { Location = new Point(30, 70), Size = new Size(400, 400), View = View.Details, FullRowSelect = true, Alignment = ListViewAlignment.SnapToGrid };
myListView.Columns.Add("NEBULAR", 200);
myListView.Columns.Add("CATEGORY", 200);
myListView.MultiSelect = false;
myListView.ItemSelectionChanged += myListView_ItemSelectionChanged;
}
static void myListView_ItemSelectionChanged(object sender, ListViewItemSelectionChangedEventArgs e)
{
if (e.IsSelected)
{
ListViewItem listViewItem = e.Item;
MessageBox.Show(listViewItem.SubItems[0].Text);
}
}
private static void populateData()
{
Hashtable nebulae = new Hashtable
{
{ "Horse Head","HII REGION"},
{"Black Widow","REFLECTION NEBULAR"},
{ "Ghost Head","HII REGION"},
{ "Witch Head" ,"PLANETARY NEBULAR"},
{ "Cat's Eye","DARK NEBULAR"},
{ "Elephant's Trunk","HII REGION"},
{ "Helix", "SUPERNOVA REMNANTS"},
{ "Rosette","REFLECTION NEBULAR"},
{ "Ant","PLANETARY NEBULAR"},
{ "Orion","HII REGION"},
{ "Eagle","REFLECTION NEBULAR"},
{ "Roesette","PLANETARY NEBULAR"},
{ "Bernad 68","SUPERNOVA REMNANTS"},
{ "Butterfly","DARK NEBULAR"},
{ "Snake","DARK NEBULAR"},
{ "Own","REFLECTION NEBULAR"},
{ "Ring", "SUPERNOVA REMNANTS"},
{ "Pelican","PLANETARY NEBULAR"},
{ "Cone","DARK NEBULAR"},
{ "Flame","REFLECTION NEBULAR"},
{ "Bumerang", "SUPERNOVA REMNANTS"}
};
int i = -1;
String[] nebulaeCategories = new string[nebulae.Values.Count];
foreach (string nebular in nebulae.Values)
{
//take note we pre-increment our variable. It will add first then return the value. So it will start at 0;
nebulaeCategories[++i] = nebular;
}
int j = -1;
foreach (string nebular in nebulae.Keys)
{
//take note we pre-increment our variable. It will add first then return the value. So it will start at 0;
myListView.Items.Add(new ListViewItem(new[] { nebular, nebulaeCategories[++j] }));
}
}
}
}
Best Regards,Oclemy.