nothing nothing - 27 days ago 6
C# Question

C# Array not clearing in listbox

I'm new to programming, and have trouble clearing my listbox to how I want. What happens is that the user is able to enter a value, and this will be stored to an array, which will then be added to a listbox. The user can clear both array/listbox at anytime. However after entering a value e.g. 123 and being displayed on the listbox, then using the clear button. Then again entering another value e.g. 555, instead of 555 being the first number in the lisbox it is: 0, 155. If I again clear then add another number e.g. 1123, output is: 0, 0, 1123. etc. I seem to have cleared only the previous elements and just placing the number to the next index. How do I empty the array/listbox so that I only add numbers to the first index and not get 0000...N displaying in my listbox.

Button to add to list box:

private void btnAdd_Click(object sender, EventArgs e)
{

if (this.index < MAX_ITEMS) // MAX_ITEMS or 10
{

// here about splitting strings as per SA's comment but may need to consider that
int dnum;

if (int.TryParse(txtInitialise.Text, out dnum))
{

numArray[this.index++] = dnum; //index is incremented immediately after it is used

txtInitialise.Text = "";

lstHoldValue.Items.Clear();
for (int i = 0; i <= numArray.Length; i++)
{
if (i < index)
{
lstHoldValue.Items.Add(numArray[i]);//show array in a listbox
}

}


}
}
}


Button to Clear:

private void btnClear_Click(object sender, EventArgs e)
{

Array.Clear(numArray, 0, numArray.Length);
lstHoldValue.Items.Clear();

}

Answer

The issue may be that you are not resetting the index value to 0 when clear is clicked. I think in the code which clears the numArray, you setting the values to 0 or you are creating another array, but remember index will still be whatever it was before clearing. If not then post your clearing code and I can help.

I just saw your clearing code and that is exactly the reason. Add this to your clear code:

this.index = 0;
Comments