Solved

My removed dont get removed

Posted on 2009-07-11
2
288 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

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
LINQ - C# to VB convertion 12 46
Problem to error 4 45
Connection String 16 43
Wav problem 4 16
Article by: Ivo
C# And Nullable Types Since 2.0 C# has Nullable(T) Generic Structure. The idea behind is to allow value type objects to have null values just like reference types have. This concerns scenarios where not all data sources have values (like a databa…
This article introduced a TextBox that supports transparent background.   Introduction TextBox is the most widely used control component in GUI design. Most GUI controls do not support transparent background and more or less do not have the…
This Micro Tutorial will give you a basic overview how to record your screen with Microsoft Expression Encoder. This program is still free and open for the public to download. This will be demonstrated using Microsoft Expression Encoder 4.
This is used to tweak the memory usage for your computer, it is used for servers more so than workstations but just be careful editing registry settings as it may cause irreversible results. I hold no responsibility for anything you do to the regist…

920 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

16 Experts available now in Live!

Get 1:1 Help Now