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

Vijay Balkawade picture Vijay Balkawade · Oct 12, 2011 · Viewed 17k times · Source


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.

Answer

Arie picture Arie · Oct 12, 2011

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();
 }