Zebra0.com

csharp files

This example will read in a CSV (comma separated values) with the name and capital of a state.
As the file is read in the name of the state will be added to a combo box and the capital will be added to a list.

When the user selects a state from the combo box, it will display the capital.

The file: Copy the list of states and capitals and save it as C:/myData/states-capitals.txt. If you save it to a different location, be sure to change the code to your location

The "Lookup" Program
This program reads the file shown above. Each line in the file is split on the comma, then the state is added to the ComboBox combobox.

  1. Start a new Windows application, name it LookupFile.
  2. Add a ComboBox combobox to the form. Name it cboStates.
  3. Add a label label named lblInfo.
  4. Add the following code (note the lines in bold that must be added in addition to the functions):
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 States
{
    public partial class Form1 : Form
    {
        List<string> capitals = new List<String> { };
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            // Opens the file and reads it line by line
            String line;
            // The Split method puts the state into parts[0], the capital into parts[1]
            String[] parts; 
            System.IO.StreamReader file =
                new System.IO.StreamReader(@"c:\mydata\states-capitals.txt");
            // Read the file  line by line. 
while ((line = file.ReadLine()) != null) { // split the name on the comma: "Maryland,Annapolis" becomes parts[0]="Maryland"; parts[1]="Annapolis"; parts = line.Split(','); // Add the state name to the combo box. cboStates.Items.Add(parts[0]); // Addthe capital to the list capitals.Add(parts[1]); } // Select the first item to display, this will cause cboStates_SelectedIndexChanged to execute also. cboStates.SelectedIndex = 0; } private void cboStates_SelectedIndexChanged(object sender, EventArgs e) { // Get the selected index and use it to display the capital from the lsit. int num = cboStates.SelectedIndex; lblInfo.Text = capitals[num]; } } }

Experiment:

Use the example to create acompletely different lookup program.

End of lesson, Next lesson: