Search code examples
datagridviewvisual-c++-2010

Display row and column value from selected cell in TextBox


I'm trying to get a DataGridView to display the HeaderText from the row and column that the users selected cell is located in. But so far, I can only get the value that is inside the selected Cell. I know this is easier to do in C#, but its a C++ exercise.

What I have so far:

 private: System::Void addAsDestinationCellToolStripMenuItem_Click(System::Object^  sender, System::EventArgs^  e) {

    if(DGV->CurrentCell != nullptr)
    {
        String^ t = dynamic_cast<String^>(DGV->CurrentCell->Value);
        dText->Text = t;
    }
         }

CurrentRow and CurrentCellAddress don't seem to work for this, but I might be trying to use them incorrectly.

Many thanks for all advice and insight.

**EDIT**

private: System::Void addAsDestinationCellToolStripMenuItem_Click(System::Object^  sender, System::EventArgs^  e) {

    if(DGV->CurrentCell != nullptr)
    {
        String^ c = DGV->Columns[DGV->CurrentCell->ColumnIndex]->HeaderText;
        String^ r = DGV->Rows[DGV->CurrentCell->RowIndex]->HeaderCell->Value->ToString();
        dText->Text = c;
        dText->Text += r;
    }
         }

Solution

  • What you need to do is get the current cell's column index value and use this to get the HeaderText for that Column in your DataGridView.

    Here's the code:

    String^ t = DGV->Columns[DGV->CurrentCell->ColumnIndex]->HeaderText;