Hi,
I can't make ContextMenu of DGV column to work. In code-behind, I created like:
var ctxMenu = new ContextMenu(); var menu1 = ctxMenu.MenuItems.Add("Edit current row"); var menu2 = ctxMenu.MenuItems.Add("Delete current row"); and assign it to dgv columns. At runtime, if I right-click a cell, the context menu doesn't pop-up. Am I missing something? Thanks and have a nice weekend.
@Berat
There are many ways: save a reference to the DGV in the ContextMenu UserData, or in a local, etc.
In general, ContextMenu links the control that showed the context menu in the SourceControl property. But in the code you posted you simply use ctxMenu.Show(location) without any reference – there is no way for the ContextMenu or child MenuItem elements to know that they are being shown in relation to a specific control.
I suggest to go for one of these two options (see attached sample too):
1- Assign the ContextMenu to DataGridViewColumn.ContextMenu property.
2- Or, use ctmMenu.Show(control) to link the ContextMenu to the control showing it.
Then in menuItem_Click, retrieve the ContextMenu using menuItem.GetContextMen() and from the ContextMenu retrieve the control that showed it using contextMenu.SourceControl.
Try the attached sample app, shows both approaches.
dataGridView1_CellMouseClick:
var ctxMenu = new ContextMenu();
var menu1 = ctxMenu.MenuItems.Add(“Soruyu Gör”);
var menu2 = ctxMenu.MenuItems.Add(“Anketi Sil”);
ctxMenu.Show(Cursor.Position);
This is the method but, when i click on menu 1 i wanna change table on the same datagridview how can i add mouseclick event for that specific issue?
Hi Luca, Alex,
Got it. Instead of the foreach loop above, I set the ContextMenu property of the DataGridView itself and it worked. WinForm doesn’t need it though.
Thanks and enjoy your weekend.
Hi,
If I may add to the discussion, apart from the datagridview contexmenu, I have been using the Row.ContextMenu without any problem.
Best,
Alex
Hi Luca,
I have a foreach loop as:
foreach (DataGridViewColumn column in dgv.Columns) { column.ContextMenu = ctxMenu; }
I have something to play with during the weekend but the same code works in WinForm though.
Thanks.
Hi Cris,
There are too many ContextMenus in the DGV (row, cell, column and grid) and we haven’t normalized that yet. The dataGrid1.ContextMenu is implemented and it works when right clicking anywhere on the grid: there was a bug that made the grid contextMenu popup only when right clicking (or long tapping) on a cell. (I’m not sure the fix was in the last update).
Best,
Luca