Using the ListBox control in .Net (C#)


In this tutorial, I will demonstrate a very simple example and use of the ListBox control. What we will be doing is loading a csv file full of data (cities worldwide) and populating the ListBox with the data read in from file. Afterwards we implement a simple search that lets the user search for a city and the list box will update search results as the text is typed.

First, we start with a form like so. I use Visual Studio to make this Windows Forms Application.

Simple forms application, contains a listbox control, a textbox for searching, and a button to load the file

Simple forms application, contains a listbox control, a textbox for searching, and a button to load the file

Once we’ve made that form, we need to obtain a csv full of data that we can use for this demo. You can get a full list/database of cities worldwide from here, it contains the city name, country, timezone, latitude and longitude: Citydb.csv

Put the .csv file inside your bin/debug folder of the project.

Next, we create a City class to represent a city object for each entry in the file.

class City
    {
        string name { get; set; }
        double lat { get; set; }
        double lon { get; set; }
        double tz { get; set; }
        public City(string name, double lat, double lon, double tz)
        {
            this.name = name;
            this.lat = lat;
            this.lon = lon;
            this.tz = tz;
        }
        public string ShowCity()
        {
            return name + "\n" + lat + ", " + lon + "\n" + 
                "Timezone: " + tz;
        }
        public override string ToString()
        {
            if(name.Contains('"'))
            {
                return name.Trim('"');
            }
            return name;
        }
    }

Afterwards, we go into the main form class (usually called Form1.cs) and begin writing our main code there to load the file into the listbox, and create the search logic.

Note that we need a few event handlers. One event handler for the Load button to load the file into the listbox, one to handle the text box Key Up event (so as to update when we type), and one to handle double clicks on the listbox, so that we can display a small message displaying details of a city.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;

namespace csvSearch
{
    public partial class Form1 : Form
    {
        //we need two lists
        //one to handle the full database of cities
        //and one to handle a filtered list after a search
        List<City> db;
        List<City> filteredList;
        public Form1()
        {
            InitializeComponent();
            db = new List<City>();
            filteredList = new List<City>();
        }
        private void loadCsv()
        {
            using (StreamReader sr = new StreamReader("citiesdb.csv"))
            {
                while (!sr.EndOfStream)
                {
                    string[] line = sr.ReadLine().Split(',');
                    City temp = new City(line[0], Convert.ToDouble(line[3]), Convert.ToDouble(line[4]), Convert.ToDouble(line[1]));
                    //we'll add to the list box and also the db list
                    listBox1.Items.Add(temp);
                    db.Add(temp);
                }
            }
            //we update the listbox to display cities
            listBox1.Invalidate();
        }
        
        private void search(string query)
        {
            filteredList.Clear();
            //any city matching or has the query will be added 
            //to the filtered list
            foreach (City c in db)
            {
                if (c.ToString().Contains(query))
                {
                    filteredList.Add(c);
                }
            }
        }
        private void filter(string phrase)
        {
            //we first need to search for valid entries
            search(phrase);
            //update listBox1 items
            listBox1.Items.Clear();
            
            foreach (City c in filteredList)
            {
                listBox1.Items.Add(c);
            }
            listBox1.Invalidate();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            //our event handler for LOAD
            loadCsv();
        }

        private void textBox1_KeyUp(object sender, KeyEventArgs e)
        {
            //make sure that even lowercase letters are valid when searching
            if (textBox1.Text != "")
            {
                string query = textBox1.Text;
                char[] a = query.ToCharArray();
                a[0] = char.ToUpper(a[0]);
                //after text has been entered, we filter results
                filter(new string(a));
            }
        }

        private void listBox1_DoubleClick(object sender, EventArgs e)
        {
            //display a small message of city details
            City temp = (City)listBox1.Items[listBox1.SelectedIndex];
            MessageBox.Show(temp.ShowCity());
        }
    }
}

Final results:
searching

Please rate and review this tutorial, I hope it has been helpful in giving an introduction to using the ListBox control in .Net. Please also subscribe or follow for future tutorials and posts. Thanks!

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s