Solved

Doing delete but get OutofINdex

Posted on 2009-07-11
2
240 Views
Last Modified: 2012-05-07
I cant seem to find my problem:

getting:
System.ArgumentOutOfRangeException was unhandled
  Message="Index was out of range. Must be non-negative and less than the size of the collection.\r\nParameter name: index"
  Source="mscorlib"
  ParamName="index"


here
        private void Delete_Click(object sender, EventArgs e)
        {
            string temp = Convert.ToString(comboBox1.SelectedItem);

            String remove = phoneTextBox.Text;
            int index = contactManager.Search(contact);
            //contactManager.Contacts[index];

            int phoneindex = contactManager.DeletePhoneNr(remove, index);
            contactManager.Contacts[index].Telephone.RemoveAt(phoneindex);

        }

in add.cs


FORM.CS
-------------------------------------------------
 
using System;
using System.IO;
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();
            path = "C:/myphonebook.ser";
            if (File.Exists(path))
            {
                // DeSerialize the object and open it
                Object obj = Serialization.binaryFileDeSerialize<ContactManager>(path);
 
                contactManager = new ContactManager();
                contactManager = (ContactManager)obj;
            }
 
            else
            {
                contactManager = new ContactManager();
            }
 
            Updater();
            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;
                contact.Telephone = addFrame.PhoneList;
                
                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;
                contact.Telephone.Clear();
                contact.Telephone = addFrame.PhoneList;
 
                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>();
            contactManager.Contacts.Sort();
            //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");
            listView1.Columns.Add("Phonenumbers");
 
            // 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);
                listviewitem.SubItems.Add(contact.Telephone.ToString());
                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)
        {
 
 
            //Make the list an object and serilaze it and save it to the harddrive
            Object obj = contactManager;
            path = "C:/myphonebook.ser";
            Serialization.binaryFileSerialize(obj, path);
           
            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 List<Phone> phonelist;
        private ContactManager contactManager;
        private Contact contact;
 
        public Add()
        {
            InitializeComponent();
            contactManager = new ContactManager();
            contact = new Contact();
            fname = "";
            lname = "";
            addButton.Enabled = false;
            phonelist = new List<Phone>();
            this.Text = "Add Contact";
            
        }
 
 
        public Add(ContactManager list, Contact contact, String text, String buttontext)
        {
            InitializeComponent();
            contactManager = list;
            this.contact = contact;
            firstnametextBox.Text = contact.FirstName;
            lastNameTextBox.Text = contact.LastName;
            comboBox1.DataSource = contact.Telephone;
            phonelist = 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
 
 
 
        public List<Phone> PhoneList
        {
            get { return phonelist; }
            set { phonelist = value; }
        } //end LastName
 
 
        private void addButton_Click(object sender, EventArgs e)
        {
            fname = firstnametextBox.Text;
            lname = lastNameTextBox.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);
        }
 
        private void addphone_Click(object sender, EventArgs e)
        {
            if (phoneTextBox.Text != "")
            {
                Phone p1 = new Phone();
                p1.Home = phoneTextBox.Text;
                phonelist.Add(p1);
                addButton.Enabled = true;
                comboBox1.DataSource = null;
                comboBox1.Items.Clear();
                comboBox1.DataSource = phonelist;
                phoneTextBox.Text = "";
            }
        }
 
        private void Delete_Click(object sender, EventArgs e)
        {
            string temp = Convert.ToString(comboBox1.SelectedItem);
 
            String remove = phoneTextBox.Text;
            int index = contactManager.Search(contact);
            //contactManager.Contacts[index];
 
            int phoneindex = contactManager.DeletePhoneNr(remove, index);
            contactManager.Contacts[index].Telephone.RemoveAt(phoneindex);
 
        }
    }
}
 
--------------------------------------
CONTACT.CS
-------------------------------------
using System;
using System.Collections.Generic;
using System.Text;
 
namespace Persons
{
    [Serializable]
    public class Contact : IContact, IComparable<Contact> 
    {
        #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
 
        #region IComparable<Contact> Members
 
       
        public int CompareTo(Contact other)
        {
            int result = this.LastName.CompareTo(other.LastName);
            if (result == 0)
            {
                result = this.FirstName.CompareTo(other.FirstName);
            }
            return result;
        }
 
 
        #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 5

Accepted Solution

by:
Imperdonato earned 500 total points
ID: 24833497
Well you have not given complete code. I'd like to see the code for ContactManager.
On which line are you getting the error?

If it is this line: contactManager.DeletePhoneNr(remove, index);
That would mean somewhere in your Delete method, you are accessing a collection object, which does not exist (maybe not anymore, because you have already deleted it).

If you are getting error on this line: contactManager.Contacts[index]....
That would mean, in the contactManager.DeletePhoneNr method, you have already deleted the object from contactManager.Contacts. Is that the case?

Check if any of the above solves your problem. If not, give the code for ContactManager.
0
 

Author Closing Comment

by:Mickeys
ID: 31602532
It was as you said:
That would mean somewhere in your Delete method, you are accessing a collection object, which does not exist (maybe not anymore, because you have already deleted it).

Thx
0

Featured Post

Optimizing Cloud Backup for Low Bandwidth

With cloud storage prices going down a growing number of SMBs start to use it for backup storage. Unfortunately, business data volume rarely fits the average Internet speed. This article provides an overview of main Internet speed challenges and reveals backup best practices.

Question has a verified solution.

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

Suggested Solutions

Summary: Persistence is the capability of an application to store the state of objects and recover it when necessary. This article compares the two common types of serialization in aspects of data access, readability, and runtime cost. A ready-to…
Calculating holidays and working days is a function that is often needed yet it is not one found within the Framework. This article presents one approach to building a working-day calculator for use in .NET.
The Email Laundry PDF encryption service allows companies to send confidential encrypted  emails to anybody. The PDF document can also contain attachments that are embedded in the encrypted PDF. The password is randomly generated by The Email Laundr…
Finds all prime numbers in a range requested and places them in a public primes() array. I've demostrated a template size of 30 (2 * 3 * 5) but larger templates can be built such 210  (2 * 3 * 5 * 7) or 2310  (2 * 3 * 5 * 7 * 11). The larger templa…

777 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