0

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.

        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();
                        }  

                  }

1 Answers1

1

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++;

and for duplicate checking maybe it is a better idea to use:

bool isContained lstHoldValue.Items.Contains(possibleDuplicate); //possibleDuplicate is object

A suggestion for code

//Get text inside text box
string textInsideTheTextbox = textBox1.Text;
//Dummy number
int dnum;
//Try parse
if (int.TryParse(textInsideTheTextbox, out dnum) == false) { /*Can not parse*/return; }
//Check duplicate
bool isDuplicate = listBox1.Items.OfType<int>().Contains(dnum);
//Show message box
if(isDuplicate) { MessageBox.Show("This number already exists!"); return; }
if(this.index < MAX_ITEMS) {
    //......
    //......
    //STUFF
    listBox1.Items.Add(dnum);
    index++;
    //......
    //......
    //STUFF
}
Hasan Emrah Süngü
  • 3,488
  • 1
  • 15
  • 33