简体   繁体   中英

C# An unhandled exception of type 'System.ArgumentOutOfRangeException' Error

I am getting the error An unhandled exception of type 'System.ArgumentOutOfRangeException' occurred in RCPYC Membership Program.exe Additional information: Index was out of range. Must be non-negative and less than the size of the collection. in the following code.

private void ApplyBtn_Click(object sender, EventArgs e)
    {
        int index = 0;
        bool loop = true;
        string text;
        List<string> Data = new List<string>();
        while (loop == true)
        {
            if (index == 17)             //If statment takes a boolean value and sets it to the correct radio button
            {
                if (BtOwnerRdio.Checked == true)
                { Data[index] = "true";}
                else if(SocialRdio.Checked == true)
                {
                    Data[index] = "false";
                }
            }
            else                        //Else statement finds the correct textbox and sets the data to its text value
            {
                if (index < 10)
                { text = "tb0" + index.ToString(); }
                else
                { text = "tb" + index.ToString(); }

                Control tb = Controls.Find(text, true).FirstOrDefault() as Control; //Finds control with the name of the text string

                if (index != 0) //Does not encrypt the ID value
                {

                    try
                    {
                        MessageBox.Show("Try");
                        Data[index] = P.encrypt(tb.Text);  //Sets the list value to the textbox text value      
//This is the line that causes the error
                    }
                    catch (Exception)
                    {
                        MessageBox.Show("Fail");   
                        throw;         **Error is thrown here**
                    }
                }
            }

            index = index + 1;  //Adds 1 to the index to move to the next loop
            if (index == Data.Count - 1) //***
            { loop = false; }   //Ends the loop if the Data list is filled
                }

The code is getting the text value from a textbox ( tb ) and adding it to a list ( Data ) but returns the error when a blank value is returned. I've checked the P.encrypt method completes when a blank value is returned and the error occurs when the string is added to the list. The index when the list is called is 1 and I have tried manually setting the list capacity to 30, however I still get the error.

MY understanding of the error is that the index is either too high or negative, however if I have manually set the list capacity to 30 how can 1 be too high or negative?

There are two miss usage in this code.

  1. You are setting the Capacity . Capacity does not mean current element quantity, it means the maximum quantity of elements.
  2. List does not act like array do.

Change Data[index] = P.encrypt(tb.Text); for Data.Add(P.encrypt(tb.Text));

I think you have some confusion about what the capacity of a list is. For a List<T> the [Capacity][1] is just the number of elements the list can hold before it needs to resize its internal data structure. Importantly this does not mean that the list has 30 entries, it means that while the size of the list is less than 30 it will not need to do any resizing. It will still start with 0 entries when first created.

I assume that you haven't actually put anything into the list yet so Data[1] will indeed be out of range. If you want 30 initialised slots then you either need to add 30 items to initialise your list or use something like an array which would have 30 items if you set its size to 30.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM