Aroueterra
Aroueterra

Reputation: 377

Trying to iterate through a DataGridView by Selected row; Receiving Index out of Bounds

I originally created a foreach DGVrow to iterate through the DGV, but this would take long since it iterates through the entire data grid which contains thousands of rows. I switched up the for each into the following:

        if (DGVmain.RowCount > 0)
        {
            if (DGVmain.SelectedCells.Count <= 0)
            {
                return;
            }
            //Source
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.Filter = "Excel Files|*.xls;*.xlsx";
            openFileDialog.ShowDialog();
            lblSuccess.Text = openFileDialog.FileName;
            lblPathings = Path.ChangeExtension(openFileDialog.FileName, null);
            int count = DGVmain.SelectedRows.Count;
            foreach (DataGridViewRow selectedRow in DGVmain.SelectedRows)
            {
                //Drag
                if (lblSuccess.Text == null)
                    return;
                //Drag
                if (lblSuccess.Text == null)
                    return;
                string dragsy = Convert.ToString(selectedRow.Cells[1].Value);
                string drag = Convert.ToString(selectedRow.Cells[2].Value);
                string drag2 = Convert.ToString(selectedRow.Cells[3].Value);
                string drag3 = Convert.ToString(selectedRow.Cells[4].Value);
                string drag4 = Convert.ToString(selectedRow.Cells[5].Value);
                string drag5 = Convert.ToString(selectedRow.Cells[6].Value);
                string drag6 = Convert.ToString(selectedRow.Cells[7].Value);
                string drag7 = Convert.ToString(selectedRow.Cells[8].Value);
                string drag8 = Convert.ToString(selectedRow.Cells[9].Value);
                string drag9 = Convert.ToString(selectedRow.Cells[10].Value);
                string drag10 = Convert.ToString(selectedRow.Cells[11].Value);
                Persona = drag;
                generateID();
                }
            }
        }

I cut out the part with where the function manipulates the data to insert it into an Excel file. It's not throwing an error, so I assume everything is sound with the syntax arrangement? What's wrong with this loop?

I only receive an index is out of bounds of the array.

Upvotes: 1

Views: 940

Answers (1)

Pikoh
Pikoh

Reputation: 7713

In C#,all arrays are 0 based. So the problem must be that you are trying to access from selectedRow.Cells[1] to selectedRow.Cells[11], when you should use selectedRow.Cells[0]to selectedRow.Cells[10]

Upvotes: 4

Related Questions