1

I have a standard DataGridView, and my last column is a DataGridViewComboBoxColumn. I would like to add an event so that when the selected index of any of the rows in that column changes, an event is triggered and I save that data to db.

I'm struggling with this for an hour or so and couldn't find any event that would trigger this...

Any help would be appreciated!!!

Irshad
  • 3,071
  • 5
  • 30
  • 51
Andrej
  • 227
  • 2
  • 3
  • 6
  • Do you mean everytime user changes an item in the last column combobox, you want to save that row data to the database? If, so I think that's not a good idea. – JPReddy Jan 28 '11 at 10:33

2 Answers2

7

In the EditingControlShowing event of the DataGridView attach a method to the combobox SelectedIndexChanged event.

For example:

private void DGV_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
  if (DGV.CurrentCell.ColumnIndex == comboColumnIndex && e.Control is ComboBox)
  {
    ComboBox comboBox = e.Control as ComboBox;
    comboBox.SelectedIndexChanged += LastColumnComboSelectionChanged;
  }
}

Now in the below method you can do whatever you want:

private void LastColumnComboSelectionChanged(object sender, EventArgs e)
{
  // Do saving work here
}
Stefan van den Akker
  • 6,661
  • 7
  • 48
  • 63
JPReddy
  • 63,233
  • 16
  • 64
  • 93
  • please notice that this approach will cause multiple registration to this event ! every time the EditingControl is about to show, you will re-register to the event. – itsho Jul 22 '12 at 21:19
2

You can try something on these lines The combobox is an editing control, so

private void dg_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
  if (dg.CurrentCell.ColumnIndex == [yourcolumnindex])
  {
    ComboBox cmbox = e.Control as ComboBox;
    cmbox.SelectedValueChanged -= new EventHandler(cmbox_SelectedValueChanged);
    cmbox.SelectedValueChanged += new EventHandler(cmbox_SelectedValueChanged);
  }
}

Now in that event you can do your stuff But is it required that for every index change you would be hitting the database?

V4Vendetta
  • 37,194
  • 9
  • 78
  • 82