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?