2016-11-19 75 views
0

我是新手,一般編程,並從C#開始我已經被告知只需通過轉換和解析就可以將項目添加到列表框中,而無需使用任何數組。然而,我似乎無法讓我的代碼工作,即時嘗試增加索引中的項目添加到lisbox中的數字。Winform如何在列表中增加項目

 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

我假設你在第一個循環中出現這個錯誤。您試圖訪問

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

但現在你有沒有lstHoldValue.Items項目,但還是儘量使用索引來訪問它。如何:以

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

和重複檢查,也許它是用一個更好的主意:

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

有人建議代碼

//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 
} 
+0

謝謝你洙多!你是一個生活救星:) – mojojooooo

+0

但現在它不再檢查它是否重複 – mojojooooo

+0

我沒有徹底檢查你的代碼,但重複檢查發生在添加任何項目之前,所以我認爲重複的代碼保持原樣。 –

相關問題