[Last Call] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 280
  • Last Modified:

Appending Text to Listbox

Program Details
User will enter a name and email address then push the button to add the information to the list box. The user adds a new name and email address and the information is appended to the list box along with the original information.

Problem
My problem is after adding the name and email for three 'customers' it will work fine. I quit the application and run it again, all text boxes are empty (good). As soon as I push the button the information from the previously run application appears and the newly entered information is appended with it. The problem is this causes duplicates (by using the same name as an example)

What I want to do is it should be a fresh application each time it starts.

Question
Is my problem with my code reside with the
StreamWriter sw = File.AppendText(filContacts);

Open in new window

Should I not append the text? Anyone have an idea how it should be written so there is not duplicate information each time the application is run?

Thank you for your help! Interface for contacts application
using System;
using System.IO;
using System.Windows.Forms;

namespace Contacts
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            string filContacts = "Contacts.txt";

            if ( !File.Exists(filContacts) ) { File.Create(filContacts); }
            {   
                StreamReader sr = new StreamReader(filContacts);
                listBox1.Items.Clear();
                while ( sr.EndOfStream != true )
                    listBox1.Items.Add(sr.ReadLine());
                sr.Close();
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            string filContacts = "Contacts.txt", strName = textBox1.Text, strEmail = textBox2.Text;

            StreamWriter sw = File.AppendText(filContacts);
            sw.WriteLine(strName);
            sw.WriteLine(strEmail);
            sw.WriteLine("");
            sw.Close();

            textBox1.Clear();
            textBox2.Clear();

            listBox1.Items.Clear();
            try
            {
                StreamReader sr = new StreamReader(filContacts);
                while ( sr.EndOfStream != true )
                    listBox1.Items.Add(sr.ReadLine());

                sr.Close();
            }
            catch ( IOException exception )
            {
                MessageBox.Show(String.Format("Problem Reading {0}", exception.Message));
            }
        }
    }

}

Open in new window

0
Michael Reeve
Asked:
Michael Reeve
  • 2
  • 2
1 Solution
 
anarki_jimbelCommented:
Honestly, I don't quite understand the problem. And code.

E.g., when writing to a file you write in the format:

Someone
someone@blabla.com

Someoneelse
someoneelse@blahblah.org

Then, when you read you add EACH line to a list. I.e. you will see :
 - name items
e-mail items
blank items

As I understand the behaviour you want is as follows:
 - You load contacts and display them
 - you want to add a new contact
     - if this contact does not exist - just add
     - if this contact exists - give a warning, or display this entry for editing or?

Pls describe scenario you want.
0
 
Michael ReeveAuthor Commented:
Application

Didn't explain it very well. It is a very simple application that just writes the contents of Textbox1 (Name) and Textbox2 (email) into the Listbox when then user clicks the contact button.

The problem is when the application has already run and contents have been already written to the listbox, it duplicates the information. If I were to close out of the application and reload it the application and without placing anything into Textbox1 or Textbox2 instead I just click the button the previous information when the application ran automatically loads. The button (or when new contents is placed into the Listbox) the old information should not show in the Listbox too, causing duplicate information.

In addition as you mentioned, if the contents already exist don't add the same name and email.

Is the code that poorly written, need honest feedback

thank you!
0
 
anarki_jimbelCommented:
First, I'd change Load event. Use "using" key word - it handles closing streams. You code causes an error if there is no file. See the snippet.

Second. I didn't get a problem. If you don't want to display data from a file - why do you write into a file? Just keep everything in a memory.
If you want to read but don't want duplicate names - before adding a new record just scan your ListBox for items with the same name. If exists - do not write into a file but display a message and/or clear text boxes.

I tried your code - no duplicates (but it adds empty entries! - stop adding if nothinf in the text boxes).
private void Form1_Load(object sender, EventArgs e)
        {
            string filContacts = "Contacts.txt";

            if (!File.Exists(filContacts))
            {
                // create a file
                using (StreamWriter outfile =
                    new StreamWriter(filContacts))
                {
                    outfile.Write("" );
                }

            }

            using(StreamReader sr = new StreamReader(filContacts))
            {
                listBox1.Items.Clear();
                while (sr.EndOfStream != true)
                    listBox1.Items.Add(sr.ReadLine());
            }

Open in new window

0
 
Michael ReeveAuthor Commented:
Very good points! Thank you very much for reviewing the code and providing feedback. I made modifications to the code (from your suggestions) and added the code you provided. Really Appreciate it!
0

Featured Post

Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

  • 2
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now