Answered Get object sent with event

bondra

Well-known member
Joined
Oct 24, 2020
Messages
77
Programming Experience
Beginner
I have a button column in a datagrid. The datagrid is printing out a list of animals. When clicking the button column I would like to get the corresponding animal object.
I found some interesting data that's being sent but this is as a string like: Doggy, Bone, Large, Button.

What I'm looking in this case is to retrieve Doggy as an object not string.

How can I achieve this?

download.png
 
Firstly, it's a DataGridView, not a datagrid. Using the actual names of things is important because it avoids confusion. There is a DataGrid control in WinForms and it has many differences to the DataGridView, so advice about one would generally be useless for the other. Be precise with your language.

As for the issue, you are hopefully handling the CellContentClick event of the grid. That will provide you with the index of the row containing the button that was clicked. You can use that to get the row itself and then get a DataRowView object from its DataBoundItem property, which you can see in your screenshot there. That is basically the row from your bound DataTable so you can get any field value you want from that using the appropriate column name.
 
Sorry about that. Difficult to keep names apart as a newbie. Thanks for pointing me in the right direction though.

Yes it's the cellContentClick event. I don't think I follow completely though. I searched the data that's being retrived from the sender but couldn't find any object correlating to the row I clicked. Only a string with every field concatinated. But that was maybe not what you was saying...?
 
Read what I posted. Do as I instructed.
I searched the data that's being retrived from the sender but couldn't find any object correlating to the row I clicked.
As I said, the event provides the index of the row. As with all event data, that's in the e parameter. Use the row index to get the row from the grid. Then do the rest of what I posted in my previously.
 
Part of the problem is because our OP inserted things into his DataGridView as an anonymous object filled with strings instead of object view models as I recommended. See his other thread regarding multiple data sources to populate a DataGridView.
 
Last edited:
Back
Top Bottom