HOW TO POPULATE A LISTBOX FROM A ,TEXT FILE AT STARTUP

Pravesh Singh

Total Post:101

Points:709
Posted by  Pravesh Singh
C# 
C#
 1368  View(s)
Ratings:
Rate this:

I need to populate a listbox from a text file at startup. I also need to have the firt 2 lines eliminated from the listbox along with all blank lines, but that isn't to important right now. I am currently stuck at getting the listbox populated at all. Here is my code so far:

struct CDCLocationEntry

{

    public string name;

}

public partial class StartupForm : Form

{

    private List<CDCLocationEntry> CDCList = new List<CDCLocationEntry>();

    public StartupForm()

    {

        InitializeComponent();

    }

    private void ReadFile()

    {

        try

        {

            StreamReader inputFile;

            string line;

           CDCLocationEntry entry = new CDCLocationEntry();

            inputFile = File.OpenText("P3S1 Data File For Import.txt");

            while (!inputFile.EndOfStream)

            {

                line = inputFile.ReadLine();

                CDCList.Add(entry);

            }

        }

        catch (Exception ex)

        {

            MessageBox.Show(ex.Message);

        }

    }

    private void DisplayText()

    {

        foreach (CDCLocationEntry entry in CDCList)

        {

            CDCLocationListBox.Items.Add(entry.name);

        }

    }

    private void StartupForm_Load(object sender, EventArgs e)

    {

        ReadFile();

        DisplayText();

    }

visual studio is say my problem is here:

struct CDCLocationEntry { public string name; }

the message I'm getting is:

Warning 1 Field 'Project_3___Section_1.CDCLocationEntry.name' is never assigned to, and will always have its default value null

none of my notes or online help is giving me an answer for this.

Any help that you can provide would be greatly appreciated

  1. ezra heywood

    Post:145

    Points:1019
    Re: How to populate a listbox from a ,text file at startup

    Hi Pravesh,


    You need to create a CDCLocationEntry instance inside the loop and assign, at this instance property name, the line coming from your file

    inputFile = File.OpenText("P3S1 Data File For Import.txt");

    while (!inputFile.EndOfStream)

    {

        CDCLocationEntry entry = new CDCLocationEntry();

        entry.name = inputFile.ReadLine();

        CDCList.Add(entry);

    }

    Your actual code creates just one instance of CDCLocationEntry outside the loop and, without assigning anything to the name property, adds this same instance in every loop.

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!