views:

2550

answers:

1

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.

+4  A: 

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());
}
Mitchell Gilman
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)?
Elie
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);
Mitchell Gilman
(Where "dataGridView1" is the name of your data grid)
Mitchell Gilman
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.
Elie
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.
Mitchell Gilman