简体   繁体   中英

Adding duplicated values to a BindingList

When I add information to a BindingList, it gets duplicated... I dont get how...

I have this class with the Lists:

public VideoRepository()
{
    videos = new BindingList<Video>();
    videosFiltered = new BindingList<Video>();
}

public BindingList<Video> videos { get; set; }
public BindingList<Video> videosFiltered { get; set; }

public void addVideo(Video video)
{
    Console.WriteLine("Size 1 " + videos.Count);
    videos.Add(video);
    videosFiltered.Add(video);
    Console.WriteLine("Size 2 " + videos.Count);
}

When I call the method addVideo the first print shows Size 1 0 and the second print shows Size 2 2 . Even when using the debuger...

What is the problem? Am I very drunk?

I've noticed that both your videos and videosFiltered have public setters. The only way you can get the behavior described is if some external code (not shown here) sets them to one and the same BindingList<Video> instance.

You'd better remove the public setters.

Or, modify the code as follows

public void addVideo(Video video)
{
    Console.WriteLine("Size 1 " + videos.Count);
    videos.Add(video);
    if (videosFiltered != videos)
        videosFiltered.Add(video);
    Console.WriteLine("Size 2 " + videos.Count);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM