hello everyone, i'm wroking with a List<string> and i want to copy it's values into a variable string each but i keep getting an index error. i declared a class library which looks like this:

public class SalesData
    {
        public List<string> GetSales( string Clientname, string Empname, string Breadtype)
        {
            List<string> getSales=new List<string>();

            string cname, ename, btype;
            cname = Clientname;
            ename = Empname;
            btype = Breadtype;

            getSales.Add(cname);
            getSales.Add(ename);
            getSales.Add(btype);

            return getSales;
           
        }
    }

and i got the values from this code

public void PreviewMeth()
        {
 
            //copy values from main page to Preview Page
            Client_Name_Main = ClientList_Lbox.SelectedItem.ToString();
            Bread_Type_Main = BreadType_Dd.SelectedItem.ToString();

            //Bread_Quantity = BreadQty_UpDown
            Deliverer_Main = Deliv_Dd.SelectedItem.ToString();

            //fill in the sales class
            gemData= fillemData.GetSales(Client_Name_Main, Deliverer_Main, Bread_Type_Main);

            
            //call up preview page
            Submit_Btn.Enabled = true;
            Preview_Page PrevPage = new Preview_Page();
            PrevPage.ShowDialog();

        }

and this bit of code is meant to get the values from the string and input them in the variables, but it gives me an index error.

private void Preview_Page_Load(object sender, EventArgs e)
        {
            
           
            myDate = newTime.Date.ToString();
            myDate_Lb.Text = myDate;

            //load client details
            prevData = getFormData.DisplayData();

            for (int i = 1; i <= 3; i++)
            {
                
                switch (i)
                {
                    case 1: C_name = prevData[i].ToString(); break;
                    case 2: D_name = prevData[i].ToString(); break;
                    case 3: B_type = prevData[i].ToString(); break;
                }
            }

            //put names up on labels
            Db_ClientName_Lb.Text = C_name;

           
        }

is there anything i'm doing wrong here guys?

Recommended Answers

All 9 Replies

Collections and arrays in C# are 0-based. That is, the first item in the collection is at index 0.
So if your prevData contains 3 items they will be indexed 0,1 and 2.

Do you have more than three items in the list?

Use the List Count method to know how many items are in your list, not some hard coded number.

hey guys, i just updated the thread so you get a full picture of what i'm working with.

@Ryshad, i actually started it off at 0 to 2 cos i have only 3 elements in there, but i got the index error message so i tried changing it to 1, and still got the error. any other suggestions based on the update to the thread?

@ddanbe, could you provide a sample code cos i'm flying blind here.

Your code hasnt really cleared much up : /

You are passing data between gemData and FillemData but i cant see where they are declared to see where the data is going. Also, you are reading the data from getFormData.DisplayData(); but again, i cant see where it is declared.

Best bet would be to debug and ensure that getFormData.DisplayData(); is returning the expected data. Also, as ddanbe pointed out, using hard coded indexes is risky, much better to use a count of the lists items:

for (int i = 0; i < prevData.Count; i++)
            {
                switch (i) {
                    case 0:
                        C_name = prevData[i].ToString();
                        break;
                    case 1:
                        D_name = prevData[i].ToString();
                        break;
                    case 2:
                        B_type = prevData[i].ToString();
                        break;
                }
            }

lol, and here i thought i had been so clear i was patting myself on the back. :).

ok, lemme include the full code so it will clarify things. the whole program is in three sections; one class library and 2 forms. first form gets data from listboxes bound to a datasource, the class library acts as an intermediary, and the second form displays the values. so here they are in the order that i have described them.

form 1

namespace Bakery_Inventory
{
    public partial class Form1 : Form
    {
        public string Client_Name_Main, Bread_Type_Main, Bread_Quantity_Main, Deliverer_Main;

        public SalesData fillemData = new SalesData();
        List<string> gemData = new List<string>();


        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            // TODO: This line of code loads data into the 'bakeDataSet2.table_EMPLOYEE' table. You can move, or remove it, as needed.
            this.table_EMPLOYEETableAdapter.Fill(this.bakeDataSet2.table_EMPLOYEE);
            // TODO: This line of code loads data into the 'bakeDataSet2.table_BREAD' table. You can move, or remove it, as needed.
            this.table_BREADTableAdapter.Fill(this.bakeDataSet2.table_BREAD);
            // TODO: This line of code loads data into the 'bakeDataSet2.table_Client' table. You can move, or remove it, as needed.
            this.table_ClientTableAdapter.Fill(this.bakeDataSet2.table_Client);
            // TODO: This line of code loads data into the 'bakeDataSet1.table_BREAD' table. You can move, or remove it, as needed.
        }

        private void Preview_Btn_Click(object sender, EventArgs e)
        {
            PreviewMeth();
        }

        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void previewToolStripMenuItem_Click(object sender, EventArgs e)
        {
            PreviewMeth();
         
        }

        public void PreviewMeth()
        {
 
            //copy values from main page to Preview Page
            Client_Name_Main = ClientList_Lbox.SelectedItem.ToString();
            Bread_Type_Main = BreadType_Dd.SelectedItem.ToString();

            //Bread_Quantity = BreadQty_UpDown
            Deliverer_Main = Deliv_Dd.SelectedItem.ToString();

            //fill in the sales class
            gemData= fillemData.GetSales(Client_Name_Main, Deliverer_Main, Bread_Type_Main);

            
            //call up preview page
            Submit_Btn.Enabled = true;
            Preview_Page PrevPage = new Preview_Page();
            PrevPage.ShowDialog();

        }


        //getting the data from this form
        public List<string> DisplayData()
        {
            return gemData;
        }

        private void Submit_Btn_Click(object sender, EventArgs e)
        {
            this.Submit_Btn.Enabled = false;
        }

        private void addNewClientToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Add_Client_Employee addMyClient = new Add_Client_Employee();
            addMyClient.ShowDialog();
        }
    }

and the class library

namespace Bakery_Inventory
{
    public class SalesData
    {
        public List<string> GetSales( string Clientname, string Empname, string Breadtype)
        {
            List<string> getSales=new List<string>();

            string cname, ename, btype;
            cname = Clientname;
            ename = Empname;
            btype = Breadtype;

            getSales.Add(cname);
            getSales.Add(ename);
            getSales.Add(btype);

            return getSales;
           
        }
    }
}

and the second form

myDate = newTime.Date.ToString();
            myDate_Lb.Text = myDate;

            //load client details
            prevData = getFormData.DisplayData();

            for (int i = 1; i <= 3; i++)
            {
                
                switch (i)
                {
                    case 1: C_name = prevData[i].ToString(); break;
                    case 2: D_name = prevData[i].ToString(); break;
                    case 3: B_type = prevData[i].ToString(); break;
                }
            }

            //put names up on labels
            Db_ClientName_Lb.Text = C_name;

           
        }

        private void CloseBtn_Click(object sender, EventArgs e)
        {
            this.Close();
        }
    }
}

i hope this clarifies issues, other than that i'm really a jerk (i hope i'm not, lol).
thanks

lol, and here i thought i had been so clear i was patting myself on the back. :).

ok, lemme include the full code so it will clarify things. the whole program is in three sections; one class library and 2 forms. first form gets data from listboxes bound to a datasource, the class library acts as an intermediary, and the second form displays the values. so here they are in the order that i have described them.

form 1

namespace Bakery_Inventory
{
    public partial class Form1 : Form
    {
        public string Client_Name_Main, Bread_Type_Main, Bread_Quantity_Main, Deliverer_Main;

        public SalesData fillemData = new SalesData();
        List<string> gemData = new List<string>();


        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            // TODO: This line of code loads data into the 'bakeDataSet2.table_EMPLOYEE' table. You can move, or remove it, as needed.
            this.table_EMPLOYEETableAdapter.Fill(this.bakeDataSet2.table_EMPLOYEE);
            // TODO: This line of code loads data into the 'bakeDataSet2.table_BREAD' table. You can move, or remove it, as needed.
            this.table_BREADTableAdapter.Fill(this.bakeDataSet2.table_BREAD);
            // TODO: This line of code loads data into the 'bakeDataSet2.table_Client' table. You can move, or remove it, as needed.
            this.table_ClientTableAdapter.Fill(this.bakeDataSet2.table_Client);
            // TODO: This line of code loads data into the 'bakeDataSet1.table_BREAD' table. You can move, or remove it, as needed.
        }

        private void Preview_Btn_Click(object sender, EventArgs e)
        {
            PreviewMeth();
        }

        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void previewToolStripMenuItem_Click(object sender, EventArgs e)
        {
            PreviewMeth();
         
        }

        public void PreviewMeth()
        {
 
            //copy values from main page to Preview Page
            Client_Name_Main = ClientList_Lbox.SelectedItem.ToString();
            Bread_Type_Main = BreadType_Dd.SelectedItem.ToString();

            //Bread_Quantity = BreadQty_UpDown
            Deliverer_Main = Deliv_Dd.SelectedItem.ToString();

            //fill in the sales class
            gemData= fillemData.GetSales(Client_Name_Main, Deliverer_Main, Bread_Type_Main);

            
            //call up preview page
            Submit_Btn.Enabled = true;
            Preview_Page PrevPage = new Preview_Page();
            PrevPage.ShowDialog();

        }


        //getting the data from this form
        public List<string> DisplayData()
        {
            return gemData;
        }

        private void Submit_Btn_Click(object sender, EventArgs e)
        {
            this.Submit_Btn.Enabled = false;
        }

        private void addNewClientToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Add_Client_Employee addMyClient = new Add_Client_Employee();
            addMyClient.ShowDialog();
        }
    }

and the class library

namespace Bakery_Inventory
{
    public class SalesData
    {
        public List<string> GetSales( string Clientname, string Empname, string Breadtype)
        {
            List<string> getSales=new List<string>();

            string cname, ename, btype;
            cname = Clientname;
            ename = Empname;
            btype = Breadtype;

            getSales.Add(cname);
            getSales.Add(ename);
            getSales.Add(btype);

            return getSales;
           
        }
    }
}

and the second form

myDate = newTime.Date.ToString();
            myDate_Lb.Text = myDate;

            //load client details
            prevData = getFormData.DisplayData();

            for (int i = 1; i <= 3; i++)
            {
                
                switch (i)
                {
                    case 1: C_name = prevData[i].ToString(); break;
                    case 2: D_name = prevData[i].ToString(); break;
                    case 3: B_type = prevData[i].ToString(); break;
                }
            }

            //put names up on labels
            Db_ClientName_Lb.Text = C_name;

           
        }

        private void CloseBtn_Click(object sender, EventArgs e)
        {
            this.Close();
        }
    }
}

i hope this clarifies issues, other than that i'm really a jerk (i hope i'm not, lol).
thanks

//load client details
            prevData = getFormData.DisplayData();

            for (int i = 1; i <= 3; i++)
            {
                
                switch (i)
                {
                    case 1: C_name = prevData[i].ToString(); break;
                    case 2: D_name = prevData[i].ToString(); break;
                    case 3: B_type = prevData[i].ToString(); break;
                }
            }

First of all, again, you should be iterating i from 0 to 2, not from 1 to 3.

Second, how do you know (at the time this code runs) that gemData has been written to? If you were getting an index error back when you had your indexes going from 0 to 2, it's because gemData had never had a three-element list written to it, because Preview_Meth was never called.

As an aside, your "for-switch" construct is a bit of a coding horror, and you should just write the three statements as follows. Also, .ToString() was superfluous too, because the values are already Strings.

C_name = prevData[0];
D_name = prevData[1];
B_type = prevData[2];

lol the perks of being a beginner. thanks Rashakil. I did a little research and i found out i could do this:

this part goes into the first form

public string ClientName { get; set; }
        public string BreadName { get; set; }
        public string EmpName { get; set; }
        public string BreadQty { get; set; }

        private static Form1 instance;

        public static Form1 GetInstance()
        {
            if ((instance == null) || (instance.IsDisposed))
                instance = new Form1();
            return instance;
        }

and deposit the values which i get through a method that calls the second form from the first

Db_ClientName_Lb.Text = Form1.GetInstance().ClientName;
            Db_TOB_Lb.Text = Form1.GetInstance().BreadName;
            Db_QOB_Lb.Text = Form1.GetInstance().BreadQty;

thanks guys. Kept me on my toes, and yes the for-switch now does look like a coding horror that i will try and stay clear off. :)

The switch isnt a coding horror in itself. It can be useful in the right situation.
The point Rashakil was making was that in your situation there was a much simpler way to do it.

The switch is much cleaner and easier to read than a long set of if..else statements. So use it when you need to perform a different action based on a variable parameter.

Glad you got this solved :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.