Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# get column header text and first row text from selected cell

Tags:

c#

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?

like image 821
Lambros Hitiris Avatar asked Dec 12 '16 18:12

Lambros Hitiris


1 Answers

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;
like image 188
Jaime Macias Avatar answered Sep 30 '22 00:09

Jaime Macias