I want to get the corresponding column header text and first row of the cell a user selected.
I have tried this but I get no message pop up.
private void factoriesTable_Click(object sender, EventArgs e)
{
string selectedRow = "";
string selectedColumn = "";
foreach (DataGridViewRow row in factoriesTable.SelectedRows)
{
selectedRow = row.Cells[0].Value.ToString();
MessageBox.Show(selectedRow);
}
foreach (DataGridViewColumn column in factoriesTable.SelectedColumns)
{
selectedColumn = column.HeaderText.ToString();
MessageBox.Show(selectedColumn);
}
}
What am I doing wrong?
If you're looking to get the selected cell and its column header you can do something like this:
string cellValue = dataGridView.SelectedCells[0].Value.ToString();
int colIndex = dataGridView.SelectedCells[0].RowIndex
string columnHeader = dataGridView.Columns[colIndex].HeaderText;
Or a one liner to get the column header:
string columnHeader = dataGridView.SelectedCells[0].OwningColumn.HeaderText;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With