nothing nothing - 1 month ago 17
C# Question

Winform Application C# Printing Whole array

I am new to c# and trying to insert a number from a textbox and I have adding a button to submit the number. I then want it to be added to the array and outputted onto the listbox. However, I am having the whole array outputted onto the listbox instead. How do I only show the number being entered?

Thanks

private const int MAX_ITEMS = 10;
private double[] numArray = new double[MAX_ITEMS]; //
private int index = 0;




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
double dnum;
if (double.TryParse(txtInitialise.Text, out dnum))
{
numArray[this.index++] = dnum; //index is incremented immediately after it is used

txtInitialise.Text = "";

//for (int i = 0; i < 10; i++)
for (int i = 0; i <= MAX_ITEMS; i++)
{
// display stuff that has been entered
if (i < index)
lstHoldValue.Items.Add(numArray[i]);//show array in a listbox


}
}
}
}

Answer

You are not clearing your listbox first. The code below should do the job:

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