Home > DeveloperSection > Forums > How to populate a listbox from a ,text file at startup
Pravesh Singh
Pravesh Singh

Total Post:101

Points:709
Posted on    December-18-2013 12:55 AM

 C# C# 
Ratings:


 1 Reply(s)
 1007  View(s)
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



ezra heywood
ezra heywood

Total Post:145

Points:1019
Posted on    December-18-2013 1:27 AM

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.


Don't want to miss updates? Please click the below button!

Follow MindStick