C#System.ArgumentOutOfRangeException:索引超出范围

时间:2014-10-19 23:04:26

标签: c# database ms-access-2003

我需要一些帮助,我对这个问题有点新意。

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();



        }

这是我第一次遇到这种问题,每次添加combobox.text都会给我这个错误,System.ArgumentOutOfRangeException:索引超出范围,必须是非负数且小于集合。

我也试过这个,但它没有解决我的问题:

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();



        }

1 个答案:

答案 0 :(得分:0)

将您的if语句更改为

(这是使用System.Linq)

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

如果你没有足够的单元格,它就不会被执行,所以你必须考虑到这个