first timer here on Stack Overflow (although I've been lurking for ages).
I'm developing a little application which contains two DataGridViews.
The second DataGridView is filled via a binding on a list of a custom class objects (the user presses a button and the list is added with a new element and re-binded to the DataGridView).
The problem I'm facing is that when I have some rows in this DataGridView (even if it's only one row in fact...), if I happen to click one of the rows to select them, Visual Studio pops up showing me the debugger, because a System.IndexOutOfRangeException happened.
It seems that when the user clicks on a row, the DataGridView throws this exception because it says I'm trying to access the -1 index of the array.
The strange fact is that this exception is thrown even if I don't have any event listening for the row selection!
Actually, there is no event at all listening on the DataGridView.
Debugger isn't helping because it's throwing the exception at the Form constructor level (it's breaking at the Application.Run(new frmMain()); so it's not telling me anything useful).
Can anybody help me please?
If you need any code let me know, and I'll provide you what I can.
Thanks!
First of all, thanks for the feedbacks.
Many Thanks to user @Trey who made me think that I had to double check my bindings.
I was binding my DataGridViews directly to my Lists<CustomType>, and not using a BindingList.
initialization:
List<CustomType> myList = new List<CustomType>();
// populating the list with some code, skipping because not relevant
myDataGridViewExample.DataSource = myList;
data insertion:
myList.Add(something);
myDataGridViewExample.DataSource = null;
myDataGridViewExample.DataSource = myList;
in this way, I was rebinding the list directly everytime I updated the list
initialization:
List<CustomType> myList = new List<CustomType>();
// populating the list with some code, skipping because not relevant
BindingList<CustomType> myBind = new BindingList<CustomType>(myList);
myDataGridViewExample.DataSource = myBind;
data insertion:
myList.Add(something);
myBind.ResetBindings();
in this way, I am only refreshing the BindingList and not touching directly the List itself.
This seem to have solved my problem, but I will edit the answer if I encounter other strange behaviours.
Thanks again, have a nice day! :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With