Winforms DataGridView 不能 select 正确的 Id 和 IndexOutOfRangeException

Winforms DataGridView cant select right Id and IndexOutOfRangeException

我正在尝试从我的数据网格中获取单击时的 ID,前 3 个工作正常,但最后一个我收到错误提示:

System.IndexOutOfRangeException: '1003位置没有线.

前 3 个元素来自 1-3,第 4 个元素的 id 为 1003 我不知道为什么,但它不应该工作吗?

加载和按钮到 select 元素:

    private void EditarComputador_Load(object sender, EventArgs e)
    {
        opBD.ListaComputadoresPreFeitos("SELECT * FROM ComputadoresPreFeitos");


        dataGridView_PreFeitos.Visible = true;
        List<ComputadoresPrefeitos> lista = new List<ComputadoresPrefeitos>();
        lista = opBD.ListaComputadoresPreFeitos();
        dataGridView_PreFeitos.DataSource = lista;
    }

    private void button1_Click(object sender, EventArgs e)
    {
        id = Convert.ToInt32(dataGridView_PreFeitos.Rows[dataGridView_PreFeitos.CurrentRow.Index].Cells[0].Value); // Pegar ID

        if (opBD.dtTabelaComputadoresPreFeitos != null && opBD.dtTabelaComputadoresPreFeitos.Rows.Count > 0)
        {
            DataRow linha = opBD.dtTabelaComputadoresPreFeitos.Rows[id];
            textBox1.Text = linha["Id_Prefeitos"].ToString();
            textBox2.Text = linha["Nome"].ToString();
            textBox3.Text = linha["Marca"].ToString();
            textBox4.Text = linha["Preco"].ToString();
        }
        
    }
       
    

opBD.dtTabelaComputadoresPreFeitos.Rows[id-1] picks the right elements but still gives me the same error

opBD.dtTabelaComputadoresPreFeitos.Rows[id-1]

////////////////

opBD.dtTabelaComputadoresPreFeitos.Rows[id] it picks one element above the other, lets say i click on id 1 it picks id 2 and still gives me the same error

opBD.dtTabelaComputadoresPreFeitos.Rows[id]

你的问题是,你试图获取 Cell 的值,1003,这是你的记录 ID,并将其用作行索引,对于有问题的记录,它应该是 3。这行不通,您应该 never 依赖与行索引匹配的 id。

下面的修复删除了将 id 设置为单元格值的行,并改用 dataGridView_PreFeitos.CurrentRow.Index 属性。

        private void button1_Click(object sender, EventArgs e)
        {
            if (opBD.dtTabelaComputadoresPreFeitos != null && opBD.dtTabelaComputadoresPreFeitos.Rows.Count > 0)
            {
                // use the dataGridView_PreFeitos.CurrentRow.Index property to get your row
                DataRow linha = opBD.dtTabelaComputadoresPreFeitos.Rows[dataGridView_PreFeitos.CurrentRow.Index];
                textBox1.Text = linha["Id_Prefeitos"].ToString();
                textBox2.Text = linha["Nome"].ToString();
                textBox3.Text = linha["Marca"].ToString();
                textBox4.Text = linha["Preco"].ToString();
            }
        }