【问题标题】:Winforms DataGridView cant select right Id and IndexOutOfRangeExceptionWinforms DataGridView 无法选择正确的 Id 和 IndexOutOfRangeException
【发布时间】:2021-03-08 19:17:14
【问题描述】:

我正在尝试从我的数据网格中获取点击 id,前 3 个工作正常,但最后一个我收到错误消息:

System.IndexOutOfRangeException: '位置 1003 处没有行。

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

加载和按钮选择元素:

    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]

【问题讨论】:

  • 不要拨打DataGridViewa GridViewDataGrid,反之亦然!!这是错误且令人困惑的,因为它们是不同的控件。始终以正确的名称称呼事物! - 另外:请勿仅将代码发布为图像!

标签: c# winforms datagridview datagrid


【解决方案1】:

您的问题是,您试图获取 Cell 的值 1003 这是您的记录 id,并将其用作行索引,对于有问题的记录应该是 3。这不起作用,您应该永远依赖 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();
            }
        }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-03-12
    • 1970-01-01
    • 1970-01-01
    • 2011-12-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-07-22
    相关资源
    最近更新 更多