Search code examples
c#winformsdatagridviewselectionchanged

How to get a specific cell in a DataGridView on selection changed


With a listbox, I have the following code to extract the item selected:

    private void inventoryList_SelectedIndexChanged(object sender, EventArgs e)
    {
        String s = inventoryList.SelectedItem.ToString();
        s = s.Substring(0, s.IndexOf(':'));
        bookDetailTable.Rows.Clear();
        ...
        more code
        ...
    }

I want to do something similar for a DataGridView, that is, when the selection changes, retrieve the contents of the first cell in the row selected. The problem is, I don't know how to access that data element.

Any help is greatly appreciated.


Solution

  • I think that this is what you're looking for. But if not, hopefully it will give you a start.

    private void dataGridView1_SelectionChanged(object sender, EventArgs e)
    {
        DataGridView dgv = (DataGridView)sender;
    
        //User selected WHOLE ROW (by clicking in the margin)
        if (dgv.SelectedRows.Count> 0)
           MessageBox.Show(dgv.SelectedRows[0].Cells[0].Value.ToString());
    
        //User selected a cell (show the first cell in the row)
        if (dgv.SelectedCells.Count > 0)
            MessageBox.Show(dgv.Rows[dgv.SelectedCells[0].RowIndex].Cells[0].Value.ToString());
    
        //User selected a cell, show that cell
        if (dgv.SelectedCells.Count > 0)
            MessageBox.Show(dgv.SelectedCells[0].Value.ToString());
    }