Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Datagridview error System.IndexOutOfRangeException: Index 0 does not have a value


I am getting one error when I am trying to populate binding source. The exception is as follows;

System.IndexOutOfRangeException: Index 0 does not have a value.
   at System.Windows.Forms.CurrencyManager.get_Item(Int32 index)
   at System.Windows.Forms.DataGridView.DataGridViewDataConnection.GetError(Int32 rowIndex)

I am using generic list to fill binding source. The code looks like,

foreach (listItem)
  {
      BindingSource.Add(listItem);
  }

I tried resetting the datasource property, but still the same issue.

Please help me to resolve this issue.

like image 528
Vijay Balkawade Avatar asked Nov 24 '25 09:11

Vijay Balkawade


1 Answers

As far as I understand, you don't have to populate BindingSource, you just have to populate the list it's bound to. That's the whole idea of binding. You bind your control to the data using bindingsource.

And then

myBindingSource.DataSource = listItem;

will do it.

Also, instead of binding your datagridview to BindingSource and your BindingSource to list, you can just bind your datagridview to BindingList. It is similar to List, but also implements IBindingList interface (when you set the BindingList object to List, it will return an object implementing IBindingList, so it'll be very similar)

Sou you can do:

myDataGridView.DataSource = myBindingList;

If properties of items on myBindingList change, the result will be reflected on datagridview by default, if the collection changed (some things were added or deleted), you may refresh it using:

 CurrencyManager cm = (CurrencyManager)this.myDataGridView.BindingContext[myBindingList];
 if (cm != null)
 {
    cm.Refresh();
 }
like image 73
Arie Avatar answered Nov 26 '25 22:11

Arie



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!