如何获取 DataGridView 中两个特定单元格的值并将它们存储在变量中

How can I get the value of two specific cells in the DataGridView and store them in variables

如何获取 DataGridView 中两个特定列中的变量,例如,我想要第一列中的 ID 和第三列中的名称。我怎样才能做到这一点?我正在尝试 RowEnter 事件,但是当我在线搜索时,我找不到任何可以跟进的内容。谢谢大家。

private void dataGridViewDocumentos_RowEnter(object sender, DataGridViewCellEventArgs e)
{
    DataGridViewRow dgvr = dataGridViewDocumentos.SelectedRows[0];
    dgvr.Cells[];

    foreach (DataGridViewRow Datarow in contentTable_dgvr.Rows)
    {
        if (dgvr.Value != null && Datarow.Cells[1].Value != null)
        {
            int contentJobId = 0;
            contentJobId = Datarow.Cells[0].Value.ToString();
               
            contentValue2 = Datarow.Cells[1].Value.ToString();

            MessageBox.Show(contentValue1);
            MessageBox.Show(contentValue2);
        }
    }
}

这就是我现在所拥有的,你们可以看到我遗漏了很多东西,我对此并不熟悉,所以如果你们能指出我需要做什么,我将不胜感激.

那么,第一个问题是,这是在网格外单击按钮吗?或者这是对已发生的特定事件的回应?我之所以这么问,是因为在您的代码示例中,您使用的是 RowEnter 事件,每次该行收到输入时都会触发该事件。我不确定那是不是你想要的。

无论如何,我的意思是您的代码示例已经差不多了。如果您想为所选行获取所选的第一列和第三列,您可以使用此代码。

private void dataGridView1_RowEnter(object sender, DataGridViewCellEventArgs e)
{
    var activeCell = dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex];

    var fistColumnCell = dataGridView1.Rows[e.RowIndex].Cells[0];

    var thirdColumnCell = dataGridView1.Rows[e.RowIndex].Cells[2];

    MessageBox.Show(fistColumnCell.Value.ToString());
    MessageBox.Show(thirdColumnCell.Value.ToString());
}

请注意,名为 DataGridViewCellEventArgs 的函数的第二个参数具有 ColumnIndexRowIndex 的属性,您可以使用它们来获取当前选定的行。

但是,如果此代码应响应用户双击单元格而触发,您可以使用 CellDoubleClick 事件

    private void dataGridView1_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
    {
        var fistColumnCell = dataGridView1.Rows[e.RowIndex].Cells[0];

        var thirdColumnCell = dataGridView1.Rows[e.RowIndex].Cells[2];

        MessageBox.Show(fistColumnCell.Value.ToString());
        MessageBox.Show(thirdColumnCell.Value.ToString());
    }