简体   繁体   中英

C# System.ArgumentOutOfRangeException:Index was out of range

I need some help, I'm kinda new to this problem..

DataGridViewCell cell = null;
        foreach (DataGridViewCell selectedCell in dataGridView1.SelectedCells)
        {
            cell = selectedCell;
            break;
        }
        if (cell != null)
        {

            DataGridViewRow row = cell.OwningRow;
            idgene.Text = row.Cells[0].Value.ToString();
            first.Text = row.Cells[1].Value.ToString();
            last.Text = row.Cells[2].Value.ToString();
            mid.Text = row.Cells[3].Value.ToString();
            address.Text = row.Cells[4].Value.ToString();
            yeaar = row.Cells[5].Value.ToString();



        }

This is the first time I encountered this kind of problem, Every time I add the combobox.text this gives me this error,System.ArgumentOutOfRangeException:Index was out of range,Must be non-negative and less than the size of the collection.

I also tried this this but it didn't solved my problem:

if (cell != null)
        {
            string yeaar = "";
            syear.Text = yeaar;
            DataGridViewRow row = cell.OwningRow;
            idgene.Text = row.Cells[0].Value.ToString();
            first.Text = row.Cells[1].Value.ToString();
            last.Text = row.Cells[2].Value.ToString();
            mid.Text = row.Cells[3].Value.ToString();
            address.Text = row.Cells[4].Value.ToString();
            yeaar = row.Cells[5].Value.ToString();



        }

change your if statement to

(this is using System.Linq)

if (cell != null && cell.OwningRow.Cells.Count() >= 6)

and if you don't have enough cells it won't execute so you will have to account for that

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM