mojojooooo mojojooooo - 20 days ago 8
C# Question

Winform How to increment items in a list

I'm new to programming in general and starting off with C# I've been told to add items to a list box without use of any arrays only by converting and parsing. However I cannot seem to get my code to work, im trying to increase the number in the index as items are added to the lisbox.

private void btnAdd_Click(object sender, EventArgs e)
{
string text = "\t" + txtInitialise.Text;
bool isDuplicate = false;

foreach (var name in lstHoldValue.Items)
{
if (name.ToString().Equals(text))
{
isDuplicate = true;
break;
}
}
if (isDuplicate)
{
MessageBox.Show("This number already exists!");
}
else
{
if (this.index < MAX_ITEMS) // MAX_ITEMS or 10
{
Convert.ToInt32(lstHoldValue.Items.Count);
// here about splitting strings as per SA's comment but may need to consider that
int dnum;
if (int.TryParse(txtInitialise.Text, out dnum))
{
(lstHoldValue.Items[this.index++]) = dnum; //index is incremented immediately after it is used
txtInitialise.Text = "";

lstHoldValue.Items.Clear();
for (int i = 0; i <= MAX_ITEMS; i++)
{
if (i < index)
{
if (radSorted.Checked == true)
{

lstHoldValue.Items.Insert(0, "\t" + Convert.ToInt32(lstHoldValue.Items[i]));//show array in a listbox
sorted();
}

}

}

}
}
}
}


The error appear on this line

(lstHoldValue.Items[this.index++]) = dnum; // 'System.ArgumentOutOfRangeException' and InvalidArgument=Value of '0' is not valid for 'index'.

Answer

I assume that you are getting this error on your very first loop. You are trying to access

lstHoldValue.Items[this.index++] //index is 0 now

but right now you have no items in lstHoldValue.Items but still try to access it using an indexer. How about:

lstHoldValue.Items.Add(dnum);
index++