I am developing a windows application using C#. I am using DataGridView
to display data. I have added a button column in that. I want to know how can I handle click event on that button in DataGridView.
相关问题
- Sorting 3 numbers without branching [closed]
- Graphics.DrawImage() - Throws out of memory except
- Generic Generics in Managed C++
- Why am I getting UnauthorizedAccessException on th
- 求获取指定qq 资料的方法
In case someone is using C# (or see Note about VB.NET below) and has reached this point, but is still stuck, please read on.
Joshua's answer helped me, but not all the way. You will notice Peter asked "Where would you get the button from?", but was unanswered.
The only way it worked for me was to do one of the following to add my event hander (after setting my DataGridView's DataSource to my DataTable and after adding the DataGridViewButtonColumn to the DataGridView):
Either:
or:
And then add the handler method (either dataGridView1_CellClick or dataGridView1_CellContentClick) shown in the various answers above.
Note: VB.NET is different from C# in this respect, because we can simply add a Handles clause to our method's signature or issue an AddHandler statement as described in the Microsoft doc's "How to: Call an Event Handler in Visual Basic"
That's answered fully here for WinForms: DataGridViewButtonColumn Class
and here: How to: Respond to Button Events in a GridView Control
for Asp.Net depending on the control you're actually using. (Your question says DataGrid, but you're developing a Windows app, so the control you'd be using there is a DataGridView...)
For example for ClickCell Event in Windows Forms.
Regards :)
Here's the better answer:
You can't implement a button clicked event for button cells in a DataGridViewButtonColumn. Instead, you use the DataGridView's CellClicked event and determine if the event fired for a cell in your DataGridViewButtonColumn. Use the event's DataGridViewCellEventArgs.RowIndex property to find out which row was clicked.
found here: button click event in datagridview
You will add button column like this in your dataGridView
Then you can add some actions inside cell click event. I found this is easiest way of doing it.
I found that Cell Click event is automatically subscribed often. So I did not need this code below. However, if your cell click event is not subscribed, then add this line of code for your dataGridView.
fine, i'll bite.
you'll need to do something like this -- obviously its all metacode.
that "hooks" the IClicked_My_Button_method method up to the button's Click event. Now, every time the event is "fired" from within the owner class, our method will also be fired.
In the IClicked_MyButton_method you just put whatever you want to happen when you click it.
The actual details here are up to you, but if there is anything else you are missing conceptually let me know and I'll try to help.