0

A DataGridView(DGV) throws and "Index was out of range" exception in some cases when its DataSource property is set to null. Of course, the error does not always occur, it is very difficult to replicate.

dgv.DataSource = null;   <-- This line throws the exception 
dgv.DataSource = dtData.DefaultView;

The stack trace is the following:

   at System.Collections.ArrayList.get_Item(Int32 index)
   at System.Windows.Forms.DataGridViewColumnCollection.get_Item(Int32 index)
   at System.Windows.Forms.DataGridView.PositionEditingControl(Boolean setLocation, Boolean setSize, Boolean setFocus)
   at System.Windows.Forms.DataGridView.PerformLayoutPrivate(Boolean useRowShortcut, Boolean computeVisibleRows, Boolean invalidInAdjustFillingColumns, Boolean repositionEditingControl)
   at System.Windows.Forms.DataGridView.ResetUIState(Boolean useRowShortcut, Boolean computeVisibleRows)
   at System.Windows.Forms.DataGridViewRowCollection.OnCollectionChanged_PreNotification(CollectionChangeAction cca, Int32 rowIndex, Int32 rowCount, DataGridViewRow& dataGridViewRow, Boolean changeIsInsertion)
   at System.Windows.Forms.DataGridViewRowCollection.OnCollectionChanged(CollectionChangeEventArgs e, Int32 rowIndex, Int32 rowCount)
   at System.Windows.Forms.DataGridViewRowCollection.AddInternal(DataGridViewRow dataGridViewRow)
   at System.Windows.Forms.DataGridView.RefreshRows(Boolean scrollIntoView)
   at System.Windows.Forms.DataGridView.OnDataSourceChanged(EventArgs e)
   at System.Windows.Forms.DataGridView.set_DataSource(Object value)
   at MonitorMedios.Corte.BusqCorte.LoadInfo() in f:\Forms\Corte\BusqCorte.cs:line 133

It is strange to me that the error occurs getting a column of the DGV: DataGridViewColumnCollection.get_Item(Int32 index)

The DGV has 14 columns, one of them is editable and uses the event CellEndEdit to store the changes in the DB, all the columns were configured using the form designer.

The DGV is using the property AutoGenerateColumns set to false.

dgv.AutoGenerateColumns = false;   <-- Code located in constructor of form 

After the error occurs for first time, it will occur again and again in the same line until the form is restarted.

I have no idea how to solve this problem, if anyone has faced something similar in the past I will appreciate any recommendation

Ayorus
  • 477
  • 7
  • 16
  • Why do you set it to null, and then to the view? Can't the first call just be removed? – Kit Jul 28 '21 at 20:15
  • Just `dgv.DataSource = dtData;`. Handle DataSourceChanged and DataBindingComplete, eventually, to prevent parsing null DataBoundItems. -- How `dtData` is generated may count. – Jimi Jul 28 '21 at 20:17

0 Answers0