| re: Inserting/Adding objects to Collections
"Vishal Somaiya" wrote...
[color=blue]
> I get a problem when I try to add the object that I created
> to the arraylist. It seems to be adding each one, but when
> I view the results of the list, it shows the last object
> passed in for each object stored within the Arraylist.[/color]
You're not adding a *new* object for each iteration, but the same object
every time. Inside the iteration, you change the values of *that* object.
I trim down you're code, so you might see it more clearly:
[color=blue]
> ClientData objClientData = new ClientData(); // <--
> ArrayList objArrayList = new ArrayList();[/color]
[color=blue]
> while (_clientCode.MoveNext() && _clientName.MoveNext()
> && _clientDetails.MoveNext())
> {
> objClientData.clientCode = _clientCode.Current.Value.ToString();
> objClientData.clientName = _clientName.Current.Value.ToString();
> objClientData.clientDetails = _clientDetails.Current.Value.ToString();
>
>
> objArrayList.Insert(j,objClientData);
> }[/color]
What you can do is simply to move the instantiation inside the iteration:
ArrayList objArrayList = new ArrayList();
while (_clientCode.MoveNext() && _clientName.MoveNext()
&& _clientDetails.MoveNext())
{
ClientData objClientData = new ClientData(); // <--
objClientData.clientCode = _clientCode.Current.Value.ToString();
objClientData.clientName = _clientName.Current.Value.ToString();
objClientData.clientDetails = _clientDetails.Current.Value.ToString();
objArrayList.Insert(j,objClientData);
}
// Bjorn A |