A.bakker
A.bakker

Reputation: 231

Get the first value from a DataGridViewRow without selecting the entire row

I have a DataGridView, I want the user to be able to select any value in it and when a button is pressed it should show the first value from that row.

private void Button_Click(object sender, EventArgs e)
{
     MessageBox.Show(Datagridview.SelectedRows[0].Cells[0].Value.ToString());
}

This of course gives an error seeing there is no row selected.

So how can I get the selected row from the selected cell to use in a way that I am able to get the value from the first cell of the row?

The only "solutions" I can find online involve forcing the user to be only able to select the entire row, not cell.

Upvotes: 0

Views: 111

Answers (1)

ASh
ASh

Reputation: 35646

you can keep cell seclection and use the row of CurrentCell

private void Button_Click(object sender, EventArgs e)
{
     var current = Datagridview.CurrentCell;
     if (current == null) return;
     MessageBox.Show(Datagridview.Rows[current.RowIndex].Cells[0].Value.ToString());
     // or with indexer:
     // MessageBox.Show(Datagridview[0, current.RowIndex].Value.ToString());
}

Upvotes: 1

Related Questions