Saturn
Saturn

Reputation: 13

C# - Adjust an auto-incremented field of an object when item is removed from Bindinglist

I have a class for a "Car" object which I have added several instances of to a Bindinglist attached to a Datagridview. I am trying to make a specific field of this object increment every time one is added to the Bindinglist, and decrement/update the sequence every time one is removed.

Example of how this is currently set up:

class Car
{
  private static int _CarNumber = 0;

  public string CarModel { get; set; }
  public bool IsInStock { get; set; }
  public int CarNumber { get; set; } = _CarNumber++;
}
public static BindingList<Car> MyCars = new BindingList<Car>();
MyCars.Add(new Car {CarModel = "Toyota", IsInStock = true});
MyCars.Add(new Car {CarModel = "Honda", IsInStock = true});
MyCars.Add(new Car {CarModel = "Mercedes", IsInStock = true});
MyCars.Add(new Car {CarModel = "Tesla", IsInStock = true});
MyCars.Add(new Car {CarModel = "Chevrolet", IsInStock = true});

This creates 5 cars objects and assigns their CarNumbers numbers as 0 - 4. This part works fine. However, if I want to remove an object from the list, the numbers will no longer be sequential--say for instance I remove an item from MyCars using MyCars.RemoveAt[2]...the remaining items will now have CarNumbers of 0, 1, 3, 4. If I used MyCars.RemoveAt[4], then next item added would still have a CarNumber of 5 despite the item before it now being 3.

What I'm wondering is, how would it be possible to make it so the CarNumber field automatically increments when adding new items, but is updated so that the numbers remain sequential when an item is removed? (so in other words, instead of the list reading 0, 1, 3, 4 with the next CarNumber being 5, the sequence would be updated to 0, 1, 2, 3 with the next CarNumber being 4) Is this even the best way to assign the CarNumber in the first place?

Thanks!

Upvotes: 0

Views: 43

Answers (1)

Omer47
Omer47

Reputation: 13

I don't think you can do this inside of Car class. Because there is no way for Car class to know if it is removed from BindingList<Car>. Also this is not best practice.

You can change CarNumber property of all the Car objects in your BindingList<Car> when you remove an item from that list. That way is more healtier than trying to manage the state of your CarNumber in Car class.

Upvotes: 0

Related Questions