Lambros Hitiris
Lambros Hitiris

Reputation: 109

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

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?

Upvotes: 5

Views: 17614

Answers (2)

Santhosh N
Santhosh N

Reputation: 82

Use This...

int x = billinggridview.CurrentCell.ColumnIndex; string text = billinggridview.Columns[x].HeaderText;

Upvotes: 0

Jaime Macias
Jaime Macias

Reputation: 847

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;

Upvotes: 13

Related Questions