-1

Every time I click any cell this is the error that pops up. Here is a copy of my code. What's wrong with it? Any suggestions?

 private void CarsdataGridView_CellClick(object sender, DataGridViewCellEventArgs e)
    {
        
        this.CarsdataGridView.DefaultCellStyle.SelectionBackColor = selectionBackColor;
        this.CarsdataGridView.DefaultCellStyle.SelectionForeColor = selectionForeColor; 

        var selectedCarData = CarsdataGridView.SelectedRows[0].DataBoundItem as CarsData;

        if (selectedCarData != null)
        { 
            txtId.Text = CarsdataGridView.SelectedRows[0].Cells[0].Value.ToString();
            txtModel.Text = CarsdataGridView.SelectedRows[0].Cells[1].Value.ToString();
            txtYear.Text = CarsdataGridView.SelectedRows[0].Cells[2].Value.ToString();
            txtGearBox.Text = CarsdataGridView.SelectedRows[0].Cells[3].Value.ToString();
            txtColor.Text = CarsdataGridView.SelectedRows[0].Cells[4].Value.ToString();
            txtMax_Speed.Text = CarsdataGridView.SelectedRows[0].Cells[5].Value.ToString();
            
        }
    }
Sawriter
  • 1
  • 1
  • 1
    Clearly one of the indexers is not valid for the collection, either `SelectedRows` or `Cells`. Also you should probably just use data-binding for this – Charlieface May 29 '22 at 13:25
  • 1
    Clicking on a cell does not mean that there are selected ones. SelectedRows will most probably be empty, thus accessing the first item when it does not exist, throws the exception. – Athanasios Kataras May 29 '22 at 13:27
  • You may also want to look into the RowSelectionMode which controls where to click to select things.. - And of course before coming here always use the [debugger](https://msdn.microsoft.com/en-us/library/y740d9d3.aspx), your very best friend in the world of coding..? – TaW May 29 '22 at 13:48

1 Answers1

0

You may be getting an error because there is not as much data as the index you tried to import in SelectedRows or Cells, adding a check to see if the data exists before you get the data can solve the problem.

Mico
  • 70
  • 6