0
votes

I have a pair of Master/Detail Datagridviews in WinForms displaying information from the following class design:

public class Roads
{
   private List<CrossStreets> _crossStreets = new List<CrossStreets>();
   public string RoadName { get; set; }
   public List<CrossStreet> CrossStreets { get { return _crossStreets;} }        
}

public class CrossStreet
{
   public string CrossStreetName { get; set;}
}

My implementation allows me to insert, update, and delete records and the magic of BindingSource() seems to take care of keeping my data relationships in sync behind the scenes. The one difficulty I am having is when the user clicks on a record in the details view, leaves it selected, and then clicks on a record in the master view that is not the parent record. At that point, the program throws a System.IndexOutOfRangeException because it seems as though it is trying to apply the current index of the child record to the new parent.

I assume there is something I can do in an event such as RowValidating to catch this but I'm not sure what. Currently, I am just doing basic checking for new rows and data validation like this:

 private void dataGridSegmentConfig_RowValidating(object sender, DataGridViewCellCancelEventArgs e)
        {


            if (dataGridViewSegmentConfig.Rows[e.RowIndex].IsNewRow)
            {
                return;
            }

//data validation logic here.
}
1

1 Answers

0
votes

The datagridview is attempting to set the index of the child row based on the selected parent row. If the parent has fewer records in it than the selected index of the child row, the IndexOutOfRangeException is thrown. To get around this, I make sure to set the child cell to null if the parent row changes.

  private void dataGridRouteConfig_RowStateChanged(object sender, DataGridViewRowStateChangedEventArgs e)
        {
            //fix for clicking the detail and then clicking a different parent.
            dataGridViewSegmentConfig.CurrentCell = null;

        }