Many times I had to create lists of structures to store my data in C#. But this time, I have an error, "Index Out of Range". I don't quite understand why, since I already did similar projects, but I would be very appreciated if someone could help me.
class mng
{
int day = 0;
List<Despesas> dias = new List<Despesas>();
public struct Despesas
{
public double transportes;
public double alimentacao;
public double vestuario;
public double agua;
public double luz;
public double educacao;
}
public mng ()
{
}
(This is where I get the error)
public void showMessage()
{
for (int i = 0; i < 31; i++)
{
MessageBox.Show("Água: " + dias[i].agua + "\nTransportes: " + dias[i].transportes);
}
}
and on Form1:
double transportes = Convert.ToDouble(txtTransportes.Text);
double agua = Convert.ToDouble(txtAgua.Text);
mng mngV = new mng(transportes, agua, educacao);
if (day < 31)
{
button1.Enabled = false;
//this is the button that enables the ShowMessage() Method.
}
else
{
button1.Enabled = true;
}
I never execute the method showMessage() before the List has 31 values, so why is it out of Index? I tried to search on the site first but couldn't find any questions with a similar problem although there are a lot with the same error. I changed the overload constructor to:
public mng(double transportes, double agua)
{
Despesas dia = new Despesas();
dia.transportes = transportes;
dia.agua = agua;
dias.Add(dia);
MessageBox.Show("Added: " + dias.Count);
day++;
}
and guess what, the dias.Count is always 1. I don't understand why...