Solved

My removed dont get removed

Posted on 2009-07-11
2
287 Views
Last Modified: 2012-05-07
I have a small probelm I cant find.

I add a contact.
I then edit it.....and in edit I change the phone nr
When this is done......I press save.
In the code I first remove the contact totally and then add it again with the new data.
The thing is I dont get ride of the phonenr I edited. I end up with two phone nr (List) instead of just a edit phone nr.

Check my code
Form1

--------------------------------

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Linq;

using System.Text;

using System.Windows.Forms;

using Persons;

using UtilitiesLibrary;
 

namespace MyPhoneBook

{

    public partial class Form1 : Form

    {

        private ContactManager contactManager;

        private string path = "";

        private string pathxml = "";
 

        public Form1()

        {

            InitializeComponent();

            contactManager = new ContactManager();

            editButton.Enabled = false;

            deleteButton.Enabled = false;
 

        }
 

        private void Add_Click(object sender, EventArgs e)

        {

            Add addFrame = new Add();
 

            if (addFrame.ShowDialog() == DialogResult.OK)

            {

                treeView1.Nodes.Clear();

                Contact contact = new Contact();

                contact.FirstName = addFrame.FirstName;

                contact.LastName = addFrame.LastName;

                Phone phone = new Phone();

                phone.Home = addFrame.Phone;

                contact.Telephone.Add(phone);

                contactManager.Contacts.Add(contact);

                

                Updater();                

            }

        }
 
 
 
 

             private void editButton_Click(object sender, EventArgs e)

        {

            Contact contact = new Contact();

            

            contact.FirstName = firstNametextBox.Text;

            contact.LastName = lastnameTextBox.Text;
 

            int index1 = contactManager.Search(contact);

            contact = contactManager.Contacts[index1];
 

            Add addFrame = new Add(contactManager, contact, "Change  Contact", "Save");
 

            if (addFrame.ShowDialog() == DialogResult.OK)

            {

                contactManager.DeleteCustomer(index1);

                contact.FirstName = addFrame.FirstName;

                contact.LastName = addFrame.LastName;

                Phone phone = new Phone();

                phone.Home = addFrame.Phone;

                contact.Telephone.Add(phone);
 

                contactManager.AddCustomer(contact);
 
 

            }

            Updater();

            

        }
 
 
 

             private void deleteButton_Click(object sender, EventArgs e)

             {

                

                 Contact contact = new Contact();

                 contact.FirstName = firstNametextBox.Text;

                 contact.LastName = lastnameTextBox.Text;
 

                 Add addFrame = new Add(contactManager, contact, "Delete  Contact", "Delete");
 

                 if (addFrame.ShowDialog() == DialogResult.OK)

                 {

                     int index = contactManager.Search(contact);

                     contactManager.DeleteCustomer(index);

                 }
 

                 Updater();

            

             }
 
 
 
 
 

        private void exitToolStripMenuItem_Click(object sender, EventArgs e)

        {

            Application.Exit();

        }
 

        private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)

        {

            firstNametextBox.Text = "";

            lastnameTextBox.Text = "";

            
 

            if (treeView1.SelectedNode.Tag != null)

            {

                Contact temp = treeView1.SelectedNode.Tag as Contact;

                firstNametextBox.Text = temp.FirstName;

                lastnameTextBox.Text = temp.LastName;

                teleComboBox.DataSource = temp.Telephone;

                editButton.Enabled = true;

                deleteButton.Enabled = true;

                firstNametextBox.Enabled = true;

                lastnameTextBox.Enabled = true;

                teleComboBox.Enabled = true;

            }       

       }
 
 
 
 
 

        private void newToolStripMenuItem_Click(object sender, EventArgs e)

        {

            //Set the TreeView to empty            

            treeView1.Nodes.Clear();
 

            //Update the GUI

            contactManager = null;

            contactManager = new ContactManager();

            

        }
 
 
 
 
 

        private void openToolStripMenuItem_Click(object sender, EventArgs e)

        {

            //If you want to open a file

            OpenFileDialog openExtensFile = new OpenFileDialog();

            openExtensFile.Title = "C#";

            openExtensFile.InitialDirectory = @"c:\";

            openExtensFile.Filter = "*.ser|*.ser*|All files (*.*)|*.*";

            openExtensFile.FilterIndex = 2;

            openExtensFile.RestoreDirectory = true;
 

            //When choosed file click OK button for opening

            if (openExtensFile.ShowDialog() == DialogResult.OK)

            {

                //Save path so you know if you have open a file (incase you should use Save button)

                path = openExtensFile.FileName.ToString();
 

                // DeSerialize the object and open it

                Object obj = Serialization.binaryFileDeSerialize<ContactManager>(openExtensFile.FileName.ToString());
 

                //Update the list and GUI

                contactManager = (ContactManager)obj;
 

            } //end if

        }
 

        private void saveToolStripMenuItem_Click(object sender, EventArgs e)

        {

            //If never saved before then we need to use Save as

            if (path.Equals(""))

            {

                saveAsToolStripMenuItem_Click(sender, e);

            } //end if
 

            else

            {

                //If saved before then we need to save it to the same file

                Object obj = contactManager;

                Serialization.binaryFileSerialize(obj, path);

            } //end else

        }
 

        private void saveAsToolStripMenuItem_Click(object sender, EventArgs e)

        {

            //If a file never been saved before we need to create a file

            SaveFileDialog saveFileDialog1 = new SaveFileDialog();

            saveFileDialog1.InitialDirectory = Convert.ToString(Environment.SpecialFolder.MyDocuments);

            saveFileDialog1.Filter = "*.ser|*.ser|All Files (*.*)|*.*";

            saveFileDialog1.FilterIndex = 1;
 

            //When choosing name of file then click ok

            if (saveFileDialog1.ShowDialog() == DialogResult.OK)

            {

                //Make the list an object and serilaze it and save it to the harddrive

                Object obj = contactManager;

                path = saveFileDialog1.FileName;

                Serialization.binaryFileSerialize(obj, saveFileDialog1.FileName);

            } //end if

        }
 
 

        private void Updater()

        {

            List<Contact> searchList = new List<Contact>();
 

            //Set the TreeView to empty            

            treeView1.Nodes.Clear();
 

            //Supress repainting

            treeView1.BeginUpdate();
 

            char outstr = ('A');
 

            //TreeNode node;

            for (int i = 1; i < 27; i++)

            {

                TreeNode node = treeView1.Nodes.Add(Convert.ToString(outstr));

                searchList = contactManager.FindALetterSearch(outstr);

                for (int j = 0; j < searchList.Count; j++)

                {

                    TreeNode Child = node.Nodes.Add(searchList[j].FirstName + " " + searchList[j].LastName);

                    Child.Tag = searchList[j];

                }

                outstr += (char)(+1);

            }
 

            //resume repainting

            treeView1.EndUpdate();
 
 

            listView1.Clear();
 

            // Used for creating listview items.

            ListViewItem listviewitem;
 

            //ListViewItem subItem = new ListViewItem();

            listView1.Columns.Add("FirstName");

            listView1.Columns.Add("LastName");
 

            // Ensure that the view is set to show details.

            listView1.View = View.Details;
 

            // Create some listview items consisting of first and last names.

            foreach (Contact contact in contactManager.Contacts)

            {

                listviewitem = new ListViewItem(contact.FirstName);

                listviewitem.SubItems.Add(contact.LastName);

                this.listView1.Items.Add(listviewitem);
 
 

            }
 

            firstNametextBox.Text = "";

            lastnameTextBox.Text = "";
 

            deleteButton.Enabled = false;

            editButton.Enabled = false;
 

            teleComboBox.DataSource = null;

            teleComboBox.Items.Clear();

            

        }
 

        private void exitButton_Click(object sender, EventArgs e)

        {

            Application.Exit();

        }
 
 
 

       

    }

}
 
 
 

--------------------------

Add.cs

-----------------------

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Linq;

using System.Text;

using System.Windows.Forms;

using Persons;

using UtilitiesLibrary;
 

namespace MyPhoneBook

{

    public partial class Add : Form

    {

        private string fname;

        private string lname;

        private string phone;
 

        public Add()

        {

            InitializeComponent();

            fname = "";

            lname = "";

            phone = "";

            this.Text = "Add Contact";

            

        }
 
 

        public Add(ContactManager list, Contact contact, String text, String buttontext)

        {

            InitializeComponent();            

            firstnametextBox.Text = contact.FirstName;

            lastNameTextBox.Text = contact.LastName;

            comboBox1.DataSource = contact.Telephone;

            phoneTextBox.Text = Convert.ToString(comboBox1.SelectedItem);

            addButton.Text = buttontext;

            this.Text  = text;

            this.DialogResult = DialogResult.OK;

           

        }
 
 
 

        //*******************************************************************

        //          FirstName

        //*******************************************************************

        public string FirstName

        {

            get { return fname; }

            set { fname = value; }

        } //end LastName
 
 
 
 

        //*******************************************************************

        //          LastName

        //*******************************************************************

        public string LastName

        {

            get { return lname; }

            set { lname = value; }

        } //end LastName
 
 

        //*******************************************************************

        //          LastName

        //*******************************************************************

        public string Phone

        {

            get { return phone; }

            set { phone = value; }

        } //end LastName
 
 

        private void addButton_Click(object sender, EventArgs e)

        {

            fname = firstnametextBox.Text;

            lname = lastNameTextBox.Text;

            phone = phoneTextBox.Text;
 

            this.DialogResult = DialogResult.OK;

        }
 

        private void closeButon_Click(object sender, EventArgs e)

        {

            this.DialogResult = DialogResult.Cancel;

        }
 

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)

        {

            phoneTextBox.Text = Convert.ToString(comboBox1.SelectedItem);

        }

    }

}
 
 
 
 

----------------------------

contactManager.cs

-----------------------------
 

using System;

using System.Collections.Generic;

using System.Text;
 

namespace Persons

{

    [Serializable]

    public class ContactManager

    {
 

        //Deklaration

        List<Contact> contact;

        bool exists = false;
 

        #region Konstruktor
 
 
 

        public ContactManager()

        {

            contact = new List<Contact>();           

            exists = true;

        } //end CustomerManager
 
 
 

         public ContactManager(List<Contact> constact)

        {

            this.contact = constact;

        } //end CustomerManager
 

        #endregion

        
 

        #region Egenskaper
 
 
 

        public int Count

        {

            get { return contact.Count; }

        } //end Count
 
 
 

        public List<Contact> Contacts

        {

            get { return contact; }

            set { contact = value; }

        } //end Customers
 
 

        #endregion
 
 

        #region Metoder
 
 
 

        public int Search(Contact cust)

        {

            int found = -1;
 

            if (exists)

            {

                for (int i = 0; i < contact.Count; i++)

                {

                    if (contact[i].FirstName.Equals(cust.FirstName) && contact[i].LastName.Equals(cust.LastName))

                    {

                        found = i;

                    } //end if                                    

                } //end for

            } //end if
 
 

            return found;

        } //end Search
 
 
 

        public List<Contact> FindALetterSearch(char letter)

        {
 

            List<Contact> returnList = new List<Contact>();
 

            if (exists)

            {

                returnList = contact.FindAll(c => c.LastName.Trim().ToLowerInvariant().StartsWith(letter.ToString().Trim().ToLowerInvariant()));
 

            } //end if            

            return returnList;
 
 

            

        } //end Search
 
 

        public void DeleteCustomer (int index) 

        {

            if (exists)

            {

                contact.RemoveAt(index);                

            } //end if        

        } //end DeleteCustomer
 
 
 

        public void ChangeCustomer(Contact cust)

        {
 

        }
 
 

        public Contact GetCustomer(int index)

        {

            return null;

        } //end GetCustomer
 
 
 
 

        public void AddCustomer(Contact cust)

        {

            if(exists)

            {

                contact.Add(cust);

            } //end if
 

            else

            {

                contact = new List<Contact>();

                contact.Add(cust);

                exists = true;

            } //end else            

        } //end AddCustomer
 
 
 
 
 

        #endregion
 

    } //end class

} //end namespace
 
 

------------------------------------

Contact.cs

-----------------------------------

using System;

using System.Collections.Generic;

using System.Text;
 

namespace Persons

{

    [Serializable]

    public class Contact : IContact

    {

        #region Attribut
 

        private string m_firstName;

        private string m_lastName;

        private List<Phone> m_phone;

        private Address m_adress;

        private Email m_email;

        private static int m_id;

        private int thiscount;
 

        #endregion
 
 

        #region Konstruktor
 
 
 

        //*******************************************************************

        //          Contact

        //*******************************************************************

        public Contact()

        {

            m_adress = new Address ();

            m_email = new Email ();

            m_lastName = string.Empty;

            m_firstName = string.Empty;

            m_phone = new List<Phone> ();
 

            thiscount = m_id++;

        } //end Contact
 
 
 

        //*******************************************************************

        //          Contact

        //*******************************************************************

        public Contact(string name, string lastname, Address adress, List<Phone> phone, Email email)

        {

            m_adress = adress;

            m_email = email;

            m_lastName = lastname;

            m_firstName = name;

            m_phone = phone;
 

            thiscount = m_id++;

        } //end Contact
 

        #endregion
 
 
 

        #region Egenskaper
 
 

        //*******************************************************************

        //          MyAdress

        //*******************************************************************

        public Address MyAdress

        {

            get { return m_adress; }

            set { m_adress = value; }

        } //end MyAdress
 
 
 

        //*******************************************************************

        //          Id

        //*******************************************************************

        public int Id

        {

            get { return thiscount; }

            set { thiscount = value; }

        } //end Id
 
 
 

        //*******************************************************************

        //          MyEmail

        //*******************************************************************

        public Email MyEmail

        {

            get { return m_email; }

            set { m_email = value; }

        } //end MyEmail
 
 

        //*******************************************************************

        //          FirstName

        //*******************************************************************

        public string FirstName

        {

            get { return m_firstName; }

            set { m_firstName = value; }

        } //end FirstName
 
 

        //*******************************************************************

        //          LastName

        //*******************************************************************

        public string LastName

        {

            get { return m_lastName; }

            set { m_lastName = value; }

        } //end LastName
 
 

        //*******************************************************************

        //          Telephone

        //*******************************************************************

        public List<Phone> Telephone

        {

            get { return m_phone; }

            set { m_phone = value; }

        } //end Telephone
 
 
 

        #endregion
 
 
 

        #region Metoder
 
 

        //*******************************************************************

        //          GetContact

        //*******************************************************************

        public string GetContact()

        {

            return m_lastName;

        } //end GetContact
 
 
 

        //*******************************************************************

        //          ToString

        //*******************************************************************

        public override string ToString()

        {

            return "" + m_firstName + m_lastName + m_adress.ToString() + m_phone.ToString() + m_email.ToString();

        } //end ToString
 

        #endregion
 
 

        #region IContact Members
 
 

        

        /// <summary>

        /// 

        /// </summary>

        /// <param name="fname"></param>

        public void setFirstName(string fname)

        {

            this.FirstName = fname;

        }
 
 
 

        /// <summary>

        /// 

        /// </summary>

        /// <param name="lname"></param>

        public void setLastName(string lname)

        {

            this.LastName = lname;

        }
 

        #endregion

    } //end class

} //end namespace
 
 

---------------------------------------

Phone.cs

--------------------------------------

using System;

using System.Collections.Generic;

using System.Text;
 

namespace Persons

{

    [Serializable]

    public class Phone

    {

        //Deklaration

        private string m_home;

        private string m_other;

        private string m_work;
 

        #region Konstruktor
 
 

        //*******************************************************************

        //          Phone

        //*******************************************************************

        public Phone()

        {

            m_home = string.Empty;

            m_other = string.Empty;

            m_work = string.Empty; ;

        } //end Phone
 
 
 

        //*******************************************************************

        //          Phone

        //*******************************************************************

        public Phone(string home, string other, string work)

        {

            m_home = home;

            m_other = other;

            m_work = work; ;

        } //end Phone
 

        #endregion
 
 
 

        #region Egenskaper
 
 
 

        //*******************************************************************

        //          Home

        //*******************************************************************

        public string Home

        {

            get { return m_home; }

            set { m_home = value; }

        } //end Home
 
 
 

        //*******************************************************************

        //          Other

        //*******************************************************************

        public string Other

        {

            get { return m_other; }

            set { m_other = value; }

        } //end Other
 
 
 

        //*******************************************************************

        //          Work

        //*******************************************************************

        public string Work

        {

            get { return m_work; }

            set { m_work = value; }

        } //end Work
 

        #endregion
 
 

        #region Metoder
 
 

        //*******************************************************************

        //          ToString

        //*******************************************************************

        public override string ToString()

        {

            return "" +m_home +m_other;

        } //end ToString
 

        #endregion
 

        

    } //end class

} //end namespace

Open in new window

0
Comment
Question by:Mickeys
2 Comments
 
LVL 41

Accepted Solution

by:
guru_sami earned 500 total points
ID: 24830515
this i what I think...
Contact contact = new Contact();
.......
 contact = contactManager.Contacts[index1];
So your contact you created earlier is overridden by the above one...because you just changing the phone number
Now your new contact instance has the old values instead of just being empty..
               
So just wondering why you need this:
----- contact = contactManager.Contacts[index1];
Not sure if you need that...
Now say if you need that.......then one thing you can do is create a totally new instace of Contact like below:
               contactManager.DeleteCustomer(index1);
               Contact newContact = new Contact();
                newContact .FirstName = addFrame.FirstName;
                newContact .LastName = addFrame.LastName;
                Phone phone = new Phone();
                phone.Home = addFrame.Phone;
                contact.Telephone.Add(phone);
                contactManager.AddCustomer(newContact );

Or before  adding a telephone number clear the Telephone List like:
contact.Telephone.Clear(); //i think thats the method...
contact.Telephone.Add(phone);


0
 

Author Comment

by:Mickeys
ID: 24830542
GREAT. Thx

This worked:  contact.Telephone.Clear();
0

Featured Post

IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

This article is for Object-Oriented Programming (OOP) beginners. An Interface contains declarations of events, indexers, methods and/or properties. Any class which implements the Interface should provide the concrete implementation for each Inter…
Performance in games development is paramount: every microsecond counts to be able to do everything in less than 33ms (aiming at 16ms). C# foreach statement is one of the worst performance killers, and here I explain why.
This demo shows you how to set up the containerized NetScaler CPX with NetScaler Management and Analytics System in a non-routable Mesos/Marathon environment for use with Micro-Services applications.
When you create an app prototype with Adobe XD, you can insert system screens -- sharing or Control Center, for example -- with just a few clicks. This video shows you how. You can take the full course on Experts Exchange at http://bit.ly/XDcourse.

747 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now