I have the following code that should generate listitems from a string that came from server. The code is as follows:
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);
}
Now my problem is,if the string array “years” has {2011,2012} the list should be 2011 and 2012. But it has 2012,2012. I am not able to find the fault in this code. Please advice.
You are reusing the same
yearLiobject in every cycle through your loop. When you do this:You are adding the same object every time. And when you change it the next time through the loop, you are changing it in every cell of your list (because it’s all a reference to the same object).
You need a new
yearLi(whatever class that’s supposed to be) instantiated in the loop.