Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DataGridView get current selected object

I need to get the currently selected object from da databound DataGridView.

I do not need the object of the current selected cell, but the object on which the whole row is based, in this case a BusinessObject whos properties make the columns of the grid.

I could go over the DataSource, but that itself is just an object and can be a BindingSource or a IBindingList or something like that - so not easy standartized way to get the wanted object.

Behind that is the need to just check the businessObject for a property called IsChanged and ask the user to save or discard the changes, before the bindingsource selects the next item. Therefore I must find out the current object inside RowValidating-Event of the DataGridView, since the BindingSource does not offer an event to stop changing before change occurs.See here for the well known problem

Thanks for reading ;-)

like image 292
Oliver Friedrich Avatar asked Jan 18 '10 09:01

Oliver Friedrich


People also ask

How to get selected row DataGridView?

To get the selected rows in a DataGridView controlUse the SelectedRows property. To enable users to select rows, you must set the SelectionMode property to FullRowSelect or RowHeaderSelect.


3 Answers

DataGridViewRow.DataBoundItem contains the 'business' object it is bound to.

like image 199
leppie Avatar answered Sep 21 '22 22:09

leppie


Here is my code put this into your Person class

 public static explicit operator Person(DataRow dr)     {         Person p = new Person();         p.adi = dr.ItemArray[0].ToString();         p.id = Int32.Parse(dr.ItemArray[1].ToString());         p.soyadi = dr.ItemArray[2].ToString();         p.kartNo = dr.ItemArray[3].ToString();         p.dogumTarihi = DateTime.Parse( dr.ItemArray[4].ToString() );         p.adres = dr.ItemArray[5].ToString();         p.meslek = dr.ItemArray[6].ToString();         p.telefon = dr.ItemArray[7].ToString();         p.gsm = dr.ItemArray[8].ToString();         p.eposta = dr.ItemArray[9].ToString();          return p;     } 

and this is a update button click

DataRow row = (dataGridView1.SelectedRows[0].DataBoundItem as DataRowView).Row; Person selected = (Person)row; 
like image 37
Kemal Duran Avatar answered Sep 23 '22 22:09

Kemal Duran


You can also use this short code.

Person selected = dataGridView1.SelectedRows[0].DataBoundItem as Person;
like image 31
Sarfaraz78615 Avatar answered Sep 23 '22 22:09

Sarfaraz78615