2
votes

I have been struggling with this issue for some hours.

This is what happens:

When my form loads, I have a DataGridView with an empty List<Entity> as datasource.

DataGridView.Datasource = null;
DataGridView.Datasource = entity_list;

First, I set it to null so as to update the DataGridView.

Then, I can add entities to that list, so that piece of code will be executed everytime I add one.

The problem I get is that after adding one entity to the list and updating the DataSource, I got an IndexOutOfRangeException when I clicked the DataGridView. It´s pretty wierd.

1
I think you misunderstand the part of "answering your own questions" Please read blog.stackoverflow.com/2011/07/… one more time - Soner Gönül
@SonerGönül what do you mean? I just read it, it says it´s fine to do it. I just spend my time writting this because I didn´t find any solution in the web or SO. I just wanted to help somebody who might be in the same condition as I were. - Andres
But you didn't phrase it in the form of a question, aka the second sentence in that link. - PiousVenom
Done. Didnt know that helping was so difficult here.. its the second time you @CL4PTR4P are not helping but bothering. I dont want points for this, I just wanted to help somebody. - Andres
@Andres: I'm not trying to be a bother. I'm simply pointing out that you're not following the guidelines of the blog. If you don't find that helpful, then I don't know what to say. - PiousVenom

1 Answers

3
votes

The problem appears because I can add entities to that List, and for some reason, if the DataSource is an empty List, this exception shows up when you try to add one entity to it.

So, the solution I used, is to asked before doing the list binding, if that list has at least 1 entity.

DataGridView.DataSource = null;
if (entity_list.Count() > 0)
    {
        DataGridView.DataSource = entity_list;
    }

And thats it! Solved! I read that using BindingLists can be a way to solve that to, but if you are using List like me, I hope this can help you out!