Question

I have a textfile which have characters like

daniel : dawson
jack : miller
frozen : mass
ralph : dcosta

I want to display text before colon in listbox1 and text after colon in textbox2 where listbox1 contains daniel and listbox2 contains dawson. codes so far,

            OpenFileDialog openFileDialog1 = new OpenFileDialog();
            openFileDialog1.Filter = "Text Files|*.txt";
            openFileDialog1.Title = "Select a Text file";
            openFileDialog1.FileName = "";
            DialogResult result = openFileDialog1.ShowDialog();
            if (result == DialogResult.OK)
            {
                string file = openFileDialog1.FileName;

                StreamReader reader = new StreamReader(file);
                List<string> users = new List<string>();
                while (!reader.EndOfStream)
                {
                    string line = reader.ReadLine();
                    string[] tokens = line.Split(new char[] { ':' }, StringSplitOptions.RemoveEmptyEntries);
                    foreach (string s in tokens)
                    {
                        if (true)
                        {

                            listBox3.Items.Add(s)  ;

                        }
                      listBox4.Items.Add(s);  


                    }
                }
}

and the output of above code is:

Lisbox1     Lisbox2
daniel      daniel
dawson      dawson
jack        jack
miller      miller

whereas I am working for

listbox1      listbox2
daniel         dawson
jack           miller

Any help will be highly appreciated, thank you

Was it helpful?

Solution

Remove the foreach and just add tokens[0] to listBox3 and tokens[1] to listBox4 like this:

if(tokens.Length >= 2)
{
    listBox3.Items.Add(tokens[0]);
    listBox4.Items.Add(tokens[1]);
}

OTHER TIPS

replace this code :

foreach (string s in tokens)
{
   if (true)
   {
        listBox3.Items.Add(s);
   }
   listBox4.Items.Add(s);
}

by :

if(tokens.Length == 2)
{
    listBox3.Items.Add(tokens[0]);
    listBox4.Items.Add(tokens[1]);
}
else
    MessageBox.Show("Invalid line input !!!!");

also to be sure that all the names does not contain whitespace add :

string line = reader.ReadLine().Trim();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top