简体   繁体   中英

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

How can I get the variables that are in two specific columns in DataGridView, for example I want the Id that is in the first column and the name that is on the third. How can I do that? I'm trying the RowEnter event but when I searched online I can't find anything that I can follow up. Thanks guys.

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

This is what I have right now, as you guys can see I'm missing a lot of things, I'm not familiar with this so if you guys can point what I need to do I'd appreciate it.

Well, the 1st question is, is this on a button click outside the grid? Or is this in response to an specific event that has happens? The reason why I ask that is because in your code sample you are using the RowEnter event which will fire everytime the row recieves input. I am not sure if that is what you want ot not.

Anyway, I mean you are pretty much there with your code sample. If you want to get the selected 1st and 3rd column for the selected row you could use this code.

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

Notice that the 2nd paramater of the function named DataGridViewCellEventArgs has properties for ColumnIndex and RowIndex which you can use to get the currently selected row.

However, if this code should fire in response to a user double clicking a cell you could use the CellDoubleClick event

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

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