Update one item in a BindingList

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Please look at the code and the following question...

public BindingList<MyStruct> myList ;

foreach ( Object item in myList )
{
MyStruct myStruct = (MyStruct)item;
myStruct .Name = "any new name" ;

///
/// Question: I need to update myList with the updated myStruct, how is the
most
/// efficient way to replace/update the old item in the list
}

Thanks
EitanB
 
EitanB,

You should cycle through the items using the indexer, and not foreach,
like so:

for (int index = 0; index < myList.Count; ++index)
{
// Get the item.
MyStruct myStruct = myList[index];

// Modify the item here.

// Assign the item back.
myList[index] = myStruct;
}

The reassignment is necessary as you are working with what I assume is a
value type, so accessing properties off instances of that type returned by
the indexer would not change the value in the list.
 
Back
Top