1

I'm racking my head over something that should be pretty simple to do. Its been a day now so I finally give up and I will ask the question. How can I actually trigger the selectionChanged event on the datagridview in .net? I would basically like to grab the row values when the user double-clicks/ or single clicks any where on a row. but I cant for the life of me get this event to fire even tough I read here that this should be the even I need to use?

private void dataGridView1_SelectionChanged(object sender, EventArgs e)
        {
            foreach (DataGridViewRow row in AddrGrid.SelectedRows)
            {
                string value1 = row.Cells[0].Value.ToString();
                string value2 = row.Cells[1].Value.ToString();
                //...
            }
        }

I have tried something similar to this but im hopeless I click on the datagrid cells or rows and this does not fire what I'm I missing?

when I click on a cell I get this event to fire.

private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {


            Addresses.aTyp = AddrGrid.Rows[AddrGrid.CurrentCell.RowIndex].Cells["Address Type"].Value.ToString();
            Addresses.seq  =  AddrGrid.Rows[AddrGrid.CurrentCell.RowIndex].Cells["Sequence"].Value.ToString();

        }

But I like to capture the double click or click on a row not just a cell. Any help would be most appreciated.

Miguel
  • 2,019
  • 4
  • 29
  • 53

4 Answers4

2
private void dataGridView_SelectionChanged(object sender, EventArgs e) 
{
     foreach (DataGridViewRow row in dataGridView1.SelectedRows) 
     {
        string value1 = row.Cells[0].Value.ToString();
        string value2 = row.Cells[1].Value.ToString();
     }
 }
MethodMan
  • 18,625
  • 6
  • 34
  • 52
2

you can use this

    private void AddrGrid_CellEnter(object sender, DataGridViewCellEventArgs e)
    {

        Addresses.aTyp = AddrGrid.Rows[AddrGrid.CurrentCell.RowIndex].Cells["Address Type"].Value.ToString();
        Addresses.seq = AddrGrid.Rows[AddrGrid.CurrentCell.RowIndex].Cells["Sequence"].Value.ToString();
    }
faheem khan
  • 471
  • 1
  • 7
  • 33
1

On your grid object lets call it 'foo'. You will do something like..

foo.SelectionChanged += dataGridView1_SelectionChanged

you will need to do that somewhere to wire the event up. I normally do it in the constructor for the form

iamkrillin
  • 6,798
  • 1
  • 24
  • 51
0

Many answers relating to the selectionchanged event for a DataGridview use "DG1.SelectedRows(0)". This is fundementally wrong. There may be multiple rows selected and the first selected row may not be the newly selected row. Unless you want to parse over all of the selected rows each time, "DG1.Rows(DG1.CurrentCell.RowIndex)" should be used

Erik Schroder
  • 63
  • 1
  • 6