2012-10-26 38 views
0

我有以下代碼應該從來自服務器的字符串生成listitems。代碼如下:listitem中的值不準確

foreach (String str in years) 
      { 

       if (string.IsNullOrEmpty(str) || str.Equals(" ")) 
       { 
        System.Diagnostics.Debug.WriteLine("empty"); 
       } 
       else 
       { 
        System.Diagnostics.Debug.WriteLine(str); 
        yearLi.Value = str; 
        yearList.Add(yearLi); 
        count = yearList.Count; 
       } 
       System.Diagnostics.Debug.WriteLine("count-->" + count); 

      } 

現在我的問題是,如果字符串數組「年」有{} 2011,2012名單應該是2011年和2012年,但它有2012,2012。我無法在此代碼中找到錯誤。請指教。

+1

告訴我們你是如何初始化'年' – egrunin

回答

8

您正在通過循環在每個循環中重複使用相同的yearLi對象。當您這樣做時:

yearList.Add(yearLi); 

您每次都添加相同的對象。當你在循環中下一次改變它時,你將在列表中的每個單元格中更改它(因爲它全部是對同一對象的引用)。

您需要一個新的yearLi(無論應該是哪個類)在循環中實例化。

+0

好呀。你絕對正確。謝謝。 – Naga