C# – 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(':'));
        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.

Best 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)

    //User selected a cell (show the first cell in the row)
    if (dgv.SelectedCells.Count > 0)

    //User selected a cell, show that cell
    if (dgv.SelectedCells.Count > 0)