简体   繁体   中英

DataGridView not updating when bound BindingList is changed

Problem: I have a C# DataGridView (Windows Forms). I've set its DataSource to a custom SortableBindingList I've found online. When I add/remove items to/from the bound list, the DataGridView doesn't update until I reset the DataSource. HOWEVER, if I don't use this custom SortableBindingList and use the standard BindingList, then it works just as expected. But I need to be able to sort. I am using EntityFramework, if that's of any help.

I've tried: Making my entities inherit INotifyPropertyChanged . This doesn't help for whatever reason. I've also tried various SortableBindingLists from the web and haven't found one to work as I need it to in my context. I've tried modifying this one I've found and have had no luck thus far. It's hard to be specific without making this post 10,000 lines long.

Asking For: A working SortableBindingList that can be sorted programatically and has binding (adding/removing from the list is reflected on the DataGridView). It would, ideally, used similarly to how I'm currently using it in the code below (to prevent too much refactoring). Or some fix to what I'm doing wrong as it's probably really obvious. The SortableBindingList I'm using was taken from this article .

Some code that may help:

Using the below binds correctly and adds/removes as expected, but I cannot sort:

this.binding.DataSource = this.context.SomeEntityList.Local.ToBindingList();

where "SomeEntityList" is of type IDbSet<SomeEntity>

--

Using any of the below code allows me to sort, but doesn't add/remove as expected:

this.binding.DataSouce = new SortableBindingList<SomeEntity>(this.context.SomeEntityList);
this.binding.DataSouce = new SortableBindingList<SomeEntity>(this.context.SomeEntityList.ToList());
this.binding.DataSouce = new SortableBindingList<SomeEntity>(this.context.SomeEntityList.Local);
this.binding.DataSouce = new SortableBindingList<SomeEntity>(this.context.SomeEntityList.Local.ToList());
this.binding.DataSouce = new SortableBindingList<SomeEntity>(this.context.SomeEntityList.Local.ToBindingList());

--

I'm setting the DataGridView's DataSouce like so:

this.DataGridView.DataSouce = this.binding;

--

Any help is much appreciated!

Thanks, Andy

I feel your pain, I struggled with the same problem for many hours. It turns out that you cannot sort a list of custom objects, regardless if it is SortableBindingList or BindingList.

Try using the BindingListView instead: http://blw.sourceforge.net/ Use the BindingListView as the soruce for your DataGridView. This will allow you to have a sortable list and it has no problems with updating after you add or remove items.

Let me know if you need an example solution.

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