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

25,078

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());
}
Share:
25,078
Elie
Author by

Elie

A programmer with a degree in CS and Biology. For my professional information go to my Linked In profile, or visit my company's site, Optimal Upgrade Consulting.

Updated on July 09, 2022

Comments

  • Elie
    Elie almost 2 years

    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.

  • Elie
    Elie over 15 years
    I think that's right, but how do I link my DataGridTable.SelectionChanged to my personal method for SelectionChanged (like the one you wrote above)?
  • Stephen de Riel
    Stephen de Riel over 15 years
    I'm not sure I understand what you mean. Are you asking how to get the control to call that function? Use the VS designer (click the control and get properties) or put this in the constructor: this.dataGridView1.SelectionChanged += new System.EventHandler(this.dataGridView1_SelectionChanged);
  • Stephen de Riel
    Stephen de Riel over 15 years
    (Where "dataGridView1" is the name of your data grid)
  • Elie
    Elie over 15 years
    Thanks, I'm new to VS designer, and when I double-clicked the control, it created the CellContentClick method, and I couldn't figure out how to get it to create the SelectionChanged method.
  • Stephen de Riel
    Stephen de Riel over 15 years
    No problem, I'm glad it worked. :-) By the way, in the VS designer, when you click a control, look at the Properties window. Click the orange lightning bolt icon at the top of the window. That will show you a list of all of the available events. Double click one to add it.