Setting up and understanding ContextMenuStrip - c#

first of all:
I´m a student that is still learning about programming.
The problem is that when I right click in a row insde the dataGridView, the RightClickDataView.Items.Add("Abgegeben"); appears as many times as I click. How can I change this?
private void dataGridViewBestellungen_MouseDown(object sender, MouseEventArgs e)
{
if(e.Button == MouseButtons.Right)
{
var hti = dataGridViewBestellungen.HitTest(e.X, e.Y);
dataGridViewBestellungen.Rows[hti.RowIndex].Selected = true;
RightClickDataView.Items.Add("Abgegeben");
RightClickDataView.Show(Cursor.Position);
var xy = dataGridViewBestellungen.SelectedRows;
foreach (DataGridViewRow row in xy)
{
//take the id in the datagridview
}
RightClickDataView.ItemClicked += new ToolStripItemClickedEventHandler(rightclickmenu_ItemClicked);
// close if mouse goes away from window
}
}
private void rightclickmenu_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
{
ToolStripItem item = e.ClickedItem;
dataGridViewBestellungen.ClearSelection();
if (e.ClickedItem.Text == "Zurück")
{
//change the state to erledigt
}
}

Just remove RightClickDataView.Items.Add("Abgegeben"); from your dataGridViewBestellungen_MouseDown and place this line on your constructor for example.

Related

Event when a menu item is highlighted

Has anyone figured out an event that fires whenever a menu item is highlighted?
I would like to display a description of each menu command in the status bar as they are highlighted. I'd like this to happen whether they are highlighted using the mouse or the keyboard.
But after considerable effort, I don't see any event like this. I even tried overriding WndProc to detect raw menu messages but found none are sent. Apparently, WinForms doesn't use the standard Windows menus.
It seems like knowing when a menu item is clicks and when it is selected (highlighted without being clicked) should be the two most important menu events. I don't know why the latter wouldn't be supported.
Anyone been able to figure this out?
In addition to the mouse events, you can add the keyboard keys part by handling the KeyUp event of the owner menu to get the selected item and display a description in a status-bar label.
public YourForm()
{
InitializeComponent();
menuStrip1.ShowItemToolTips = false;
menuStrip1.KeyUp += OnToolStripKeyUp;
foreach (var item in GetAllToolStripItems(menuStrip1.Items))
{
item.AutoToolTip = false;
item.MouseEnter += OnToolStripItemMouseEnter;
item.MouseLeave += OnToolStripItemMouseLeave;
if (item.GetCurrentParent() is ToolStrip dm)
{
dm.ShowItemToolTips = false;
dm.KeyUp -= OnToolStripKeyUp;
dm.KeyUp += OnToolStripKeyUp;
}
}
}
private void OnToolStripItemMouseEnter(object sender, EventArgs e)
{
sbrLabel.Text = (sender as ToolStripItem).ToolTipText;
}
private void OnToolStripItemMouseLeave(object sender, EventArgs e)
{
sbrLabel.Text = "Ready";
}
private void OnToolStripKeyUp(object sender, KeyEventArgs e)
{
var s = sender as ToolStrip;
var selItem = s.Items.OfType<ToolStripMenuItem>().FirstOrDefault(x => x.Selected);
sbrLabel.Text = selItem?.ToolTipText;
}
private IEnumerable<ToolStripItem> GetAllToolStripItems(ToolStripItemCollection tsic)
{
foreach (var tsi in tsic.Cast<ToolStripItem>())
{
yield return tsi;
if (tsi is ToolStripDropDownItem tsddi && tsddi.HasDropDown)
foreach (var ddi in GetAllToolStripItems(tsddi.DropDownItems))
yield return ddi;
}
}
With #dr.null's help, I got this working. Here's my version of the code.
private void InitializeMenuStatus(ToolStrip toolStrip)
{
toolStrip.ShowItemToolTips = false;
toolStrip.KeyUp += ToolStrip_KeyUp;
foreach (ToolStripItem toolStripItem in toolStrip.Items)
{
toolStripItem.AutoToolTip = false;
toolStripItem.MouseEnter += ToolStripItem_MouseEnter;
toolStripItem.MouseLeave += ToolStripItem_MouseLeave;
if (toolStripItem is ToolStripDropDownItem dropDownItem)
InitializeMenuStatus(dropDownItem.DropDown);
}
}
private ToolStripItem? SelectedMenuItem = null;
private void SetSelectedMenuItem(ToolStripItem? item)
{
if (!ReferenceEquals(item, SelectedMenuItem))
{
SelectedMenuItem = item;
lblStatus.Text = item?.ToolTipText ?? string.Empty;
}
}
private void ToolStripItem_MouseEnter(object? sender, EventArgs e)
{
if (sender is ToolStripMenuItem menuItem && menuItem.Selected)
SetSelectedMenuItem(menuItem);
}
private void ToolStripItem_MouseLeave(object? sender, EventArgs e)
{
SetSelectedMenuItem(null);
}
private void ToolStrip_KeyUp(object? sender, KeyEventArgs e)
{
if (sender is ToolStripDropDownMenu dropDownMenu)
{
ToolStripMenuItem? menuItem = dropDownMenu.Items.OfType<ToolStripMenuItem>()
.Where(m => m.Selected)
.FirstOrDefault();
SetSelectedMenuItem(menuItem);
}
}
Why a Selected event was never added to menu items escapes me. I have suggested that it be added. If you agree, please go and show your support for that request.
If anyone's interested, I spent some time fine tuning this code and ended up making a free component, now published as a NuGet package. You can view the code on GitHub

Drag & Drop between DataGridView

I have copied some code and modified it to suit my application. And I will continue to tweak and clean up the code until I am statisfied with it. But I have encountered a little error. I have two datagridviews and wish to move datagridrows from one to another. However, while the drag&drop events all fire, the dataGridView_Routes_DragDrop() will execute the log command because there is no data in e.Data.GetData. What have I done wrong? Am I missing something? I've tried to look through several guides but nothing specifically covers this issue.
How can I get the datagrid pass the dragged datagridrow over to the other datagrid?
/* Drag & Drop */
private Rectangle dragBoxFromMouseDown;
private int rowIndexFromMouseDown;
private void dataGridView_Trips_MouseMove(object sender, MouseEventArgs e)
{
if ((e.Button & MouseButtons.Left) == MouseButtons.Left)
{
// If the mouse moves outside the rectangle, start the drag.
if (dragBoxFromMouseDown != Rectangle.Empty && !dragBoxFromMouseDown.Contains(e.X, e.Y))
{
// Proceed with the drag and drop, passing in the list item.
DragDropEffects dropEffect = dataGridView_Trips.DoDragDrop(dataGridView_Trips.Rows[rowIndexFromMouseDown], DragDropEffects.Copy);
}
}
}
private void dataGridView_Trips_MouseDown(object sender, MouseEventArgs e)
{
// Get the index of the item the mouse is below.
rowIndexFromMouseDown = dataGridView_Trips.HitTest(e.X, e.Y).RowIndex;
if (rowIndexFromMouseDown != -1)
{
// Remember the point where the mouse down occurred.
// The DragSize indicates the size that the mouse can move
// before a drag event should be started.
Size dragSize = SystemInformation.DragSize;
// Create a rectangle using the DragSize, with the mouse position being
// at the center of the rectangle.
dragBoxFromMouseDown = new Rectangle(new Point(e.X - (dragSize.Width / 2), e.Y - (dragSize.Height / 2)), dragSize);
}
else
// Reset the rectangle if the mouse is not over an item in the ListBox.
dragBoxFromMouseDown = Rectangle.Empty;
}
private void dataGridView_Routes_DragOver(object sender, DragEventArgs e)
{
e.Effect = DragDropEffects.Copy;
}
private void dataGridView_Routes_DragDrop(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(typeof(DataRowView)))
{
// The mouse locations are relative to the screen, so they must be
// converted to client coordinates.
Point clientPoint = dataGridView_Routes.PointToClient(new Point(e.X, e.Y));
// If the drag operation was a copy then add the row to the other control.
if (e.Effect == DragDropEffects.Copy)
{
DataGridViewRow rowToMove = e.Data(typeof(DataGridViewRow)) as DataGridViewRow;
dataGridView_Routes.Rows.Add(rowToMove);
}
}
else
{
log("Geen data! #01", "Fout");
}
}
/* End Drag & Drop */
I don't know. But the following function has been adjusted and it works as intended. Not quite sure how the previous code broke.
EDIT: The typeof was written with DataViewRow instead of DataGridViewRow. Fail.
private void dataGridView_Routes_DragDrop(object sender, DragEventArgs e)
{
try
{
if (e.Data.GetDataPresent(typeof(DataGridViewRow)))
{
// The mouse locations are relative to the screen, so they must be
// converted to client coordinates.
Point clientPoint = dataGridView_Routes.PointToClient(new Point(e.X, e.Y));
// If the drag operation was a copy then add the row to the other control.
if (e.Effect == DragDropEffects.Copy)
{
DataGridViewRow Row = (DataGridViewRow)e.Data.GetData(typeof(DataGridViewRow));
dataGridView_Routes.Rows.Add(Row.Cells[0].Value, Row.Cells[1].Value, Row.Cells[2].Value);
}
}
else
{
log("Geen data! #01", "Fout");
}
}
catch (Exception msg)
{
log(msg.Message,"Fout");
}
}
This solution is for the people who have the datagridViews bound to customObjects. It works like a charm with multiple selection. Suggestions are accepted.
Assuming you want to drag from datagridview1 to datagridview2
//datagridview1 is bound to this BindingList
BindingList<myObject> object_bound_list1;
//datagridview2 is bound to this BindingList
BindingList<myObject> object_bound_list2;
List<myObject> selected_Object_list = new List<myObject>();
List<int> selected_pos_list = new List<int>();
private void dataGridView1_MouseMove(object sender, MouseEventArgs e)
{
if ((e.Button & MouseButtons.Left) == MouseButtons.Left)
{
// Proceed with the drag and drop, passing in the list item.
DragDropEffects dropEffect = dataGridView1.DoDragDrop(
selected_Object_list,
DragDropEffects.Move);
}
}
private void dataGridView1_MouseDown(object sender, MouseEventArgs e)
{
// Get the index of the item the mouse is below.
int rowIndexFromMouseDown = dataGridView1.HitTest(e.X, e.Y).RowIndex;
//if shift key is not pressed
if (Control.ModifierKeys != Keys.Shift && Control.ModifierKeys != Keys.Control)
{
//if row under the mouse is not selected
if (!selected_pos_list.Contains(rowIndexFromMouseDown) && rowIndexFromMouseDown > 0)
{
//if there only one row selected
if (dataGridView1.SelectedRows.Count == 1)
{
//select the row below the mouse
dataGridView.ClearSelection();
dataGridView1.Rows[rowIndexFromMouseDown].Selected = true;
}
}
}
//clear the selection lists
selected_Object_list.Clear();
selected_pos_list.Clear();
//add the selected objects
foreach (DataGridViewRow row in dataGridView1.SelectedRows)
{
selected_Object_list.Add(object_bound_list1[row.Index]);
selected_pos_list.Add(row.Index);
}
}
private void dataGridView2_DragOver(object sender, DragEventArgs e)
{
e.Effect = DragDropEffects.Move;
}
private void dataGridView2_DragDrop(object sender, DragEventArgs e)
{
if (e.Effect == DragDropEffects.Move)
{
foreach (var item in selected_Object_list)
{
object_bound_list2.Add(item);
}
}
}

How to create a dynamically built Context Menu clickEvent

I have a DataGridView and a context menu that opens when you right click a specific column.
What shows up in the context menu is dependant on what's in the field clicked on - paths to multiple files (the paths are manipulated to create a full UNC path to the correct file).
The only problem is that I can't get the click working.
I did not drag and drop the context menu from the toolbar, I created it programmically.
I figured that if I can get the path (let's call it ContextMenuChosen) to show up in MessageBox.Show(ContextMenuChosen); I could set the same to System.Diagnostics.Process.Start(ContextMenuChosen);
The Mydgv_MouseUp event below actually works to the point where I can get it to fire off MessageBox.Show("foo!"); when something in the context menu is selected but that's where it ends. I left in a bunch of comments below showing what I've tried when it one of the paths are clicked. Some result in empty strings, others error (Object not set to an instance...).
I searched code all day yesterday but couldn't find another way to hook up a dynamically built Context Menu clickEvent.
Code and comments:
ContextMenu m = new ContextMenu();
// SHOW THE RIGHT CLICK MENU
private void Mydgv_MouseClick(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Right)
{
int currentMouseOverCol = Mydgv.HitTest(e.X, e.Y).ColumnIndex;
int currentMouseOverRow = Mydgv.HitTest(e.X, e.Y).RowIndex;
if (currentMouseOverRow >= 0 && currentMouseOverCol == 6)
{
string[] paths = myPaths.Split(';');
foreach (string path in paths)
{
string UNCPath = "\\\\1.1.1.1\\c$\\MyPath\\";
string FilePath = path.Replace("c:\\MyPath\\", #"");
m.MenuItems.Add(new MenuItem(UNCPath + FilePath));
}
}
m.Show(Mydgv, new Point(e.X, e.Y));
}
}
// SELECTING SOMETHING IN THE RIGHT CLICK MENU
private void Mydgv_MouseUp(object sender, MouseEventArgs e)
{
DataGridView.HitTestInfo hitTestInfo;
if (e.Button == MouseButtons.Right)
{
hitTestInfo = Mydgv.HitTest(e.X, e.Y);
// If column is first column
if (hitTestInfo.Type == DataGridViewHitTestType.Cell && hitTestInfo.ColumnIndex == 6)
{
//MessageBox.Show(m.ToString());
////MessageBox.Show(m.Tag.ToString());
//MessageBox.Show(m.Name.ToString());
//MessageBox.Show(m.MenuItems.ToString());
////MessageBox.Show(m.MdiListItem.ToString());
// MessageBox.Show(m.Name);
//if (m.MenuItems.Count > 0)
//MessageBox.Show(m.MdiListItem.Text);
//MessageBox.Show(m.ToString());
//MessageBox.Show(m.MenuItems.ToString());
//Mydgv.ContextMenu.Show(m.Name.ToString());
//MessageBox.Show(ContextMenu.ToString());
//MessageBox.Show(ContextMenu.MenuItems.ToString());
//MenuItem.text
//MessageBox.Show(this.ContextMenu.MenuItems.ToString());
}
m.MenuItems.Clear();
}
}
I'm very close to completing this so any help would be much appreciated.
I don't see an event handler wired to your menu item, so that something will happen when you click it:
void menu_Click(object sender, EventArgs e) {
MessageBox.Show(((MenuItem)sender).Text);
}
Then attach it when you add the menu item to the context menu:
MenuItem mi = new MenuItem(UNCPath + FilePath);
mi.Click += menu_Click;
m.MenuItems.Add(mi);
You may handle CellMouseDown like this when you when you right click a cell of a specific column. The specific column is achieved by e.ColumnIndex check
Aditionally, you can use GetCellDisplayRectangle instead of hittest
ContextMenu cm = new ContextMenu();
void dataGridView1_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
{
if (e.Button == MouseButtons.Right)
{
if (e.ColumnIndex == 0)
{
cm.MenuItems.Clear();
var mi = new MenuItem("C:\temp");
mi.MenuItems.Add(mi);
// handle menu item click event here [as required]
mi.Click += OnMenuItemClick;
cm.MenuItems.Add(0, mi);
var bounds = dataGridView1.GetCellDisplayRectangle(e.ColumnIndex, e.RowIndex, false);
if (sender != null)
{
cm.Show(sender as DataGridView, new Point(bounds.X, bounds.Y));
}
}
}
}
void OnMenuItemClick(object sender, EventArgs e)
{
MessageBox.Show(((MenuItem)sender).Text);
}

C# How to select ListBox item with a RightClick?

I have tried a lot of methods for this and done hours of research, but it just never seems to work for me.
This is my current code, and I don't know why it shouldn't work.
private void listBox1_MouseDown(object sender, MouseEventArgs e)
{
listBox1.SelectedIndex = listBox1.IndexFromPoint(e.X, e.Y);
if (e.Button == MouseButtons.Right)
{
contextMenuStrip1.Show();
}
}
Also I don't care about the context menu that can be removed I am just looking for a way to make the right mouse button select the item I click on.
Any Ideas?
You are close, you just forgot to select the item. Fix:
private void listBox1_MouseUp(object sender, MouseEventArgs e) {
if (e.Button == MouseButtons.Right) {
var item = listBox1.IndexFromPoint(e.Location);
if (item >= 0) {
listBox1.SelectedIndex = item;
contextMenuStrip1.Show(listBox1, e.Location);
}
}
}
private void lstFiles_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Right) //(1)
{
int indexOfItemUnderMouseToDrag;
indexOfItemUnderMouseToDrag = lstFiles.IndexFromPoint(e.X, e.Y); //(2)
if (indexOfItemUnderMouseToDrag != ListBox.NoMatches)
{
lstFiles.SelectedIndex = indexOfItemUnderMouseToDrag; //(3)
}
}
}
Each control inherits ContextMenu property from Control class. Assign your context menu object to the ContextMenu property of your list box control and WinForms will handle it automatically for you.
private void listBox1_MouseUp(object sender, MouseEventArgs e)
{
if (e.Button== MouseButtons.Right)
{
int nowIndex = e.Y / listBox1.ItemHeight;
if (nowIndex < listBox1.Items.Count)
{
listBox1.SelectedIndex = e.Y / listBox1.ItemHeight;
}
else
{
//Out of rang
}
}
}
I do not know much in C#, but I tried :)
I was dealing with the same issue. From Hans Passant's reply I tweaked it a little to get the below code. I also found that I didn't need to put contextMenuStrip1.Show(listBox1, e.Location); in there at all. It was automatically called for me.
(I'm using Visual Studio 2010 Ultimate with and compiling at .NET 4. I also verified that the below code works for BOTH MouseUp and MouseDown.)
private void OnMouseDown(object sender, MouseEventArgs args)
{
if (args.Button == MouseButtons.Right)
{
var item = this.IndexFromPoint(args.Location);
if (item >= 0 && this.SelectedIndices.Contains(item) == false)
{
this.SelectedItems.Clear();
this.SelectedIndex = item;
}
}
}

Right click to select a row in a Datagridview and show a menu to delete it

I have few columns in my DataGridView, and there is data in my rows. I saw few solutions in here, but I can not combine them!
Simply a way to right-click on a row, it will select the whole row and show a menu with an option to delete the row and when the option selected it will delete the row.
I made few attempts but none is working and it looks messy. What should I do?
I finally solved it:
In Visual Studio, create a ContextMenuStrip with an item called "DeleteRow"
Then at the DataGridView link the ContextMenuStrip
Using the code below helped me getting it work.
this.MyDataGridView.MouseDown += new System.Windows.Forms.MouseEventHandler(this.MyDataGridView_MouseDown);
this.DeleteRow.Click += new System.EventHandler(this.DeleteRow_Click);
Here is the cool part
private void MyDataGridView_MouseDown(object sender, MouseEventArgs e)
{
if(e.Button == MouseButtons.Right)
{
var hti = MyDataGridView.HitTest(e.X, e.Y);
MyDataGridView.ClearSelection();
MyDataGridView.Rows[hti.RowIndex].Selected = true;
}
}
private void DeleteRow_Click(object sender, EventArgs e)
{
Int32 rowToDelete = MyDataGridView.Rows.GetFirstRow(DataGridViewElementStates.Selected);
MyDataGridView.Rows.RemoveAt(rowToDelete);
MyDataGridView.ClearSelection();
}
For completness of this question, better to use a Grid event rather than mouse.
First Set your datagrid properties:
SelectionMode to FullRowSelect
and
RowTemplate / ContextMenuStrip to a context menu.
Create the CellMouseDown event:-
private void myDatagridView_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
{
if (e.Button == MouseButtons.Right)
{
int rowSelected = e.RowIndex;
if (e.RowIndex != -1)
{
this.myDatagridView.ClearSelection();
this.myDatagridView.Rows[rowSelected].Selected = true;
}
// you now have the selected row with the context menu showing for the user to delete etc.
}
}
private void dgvOferty_CellContextMenuStripNeeded(object sender, DataGridViewCellContextMenuStripNeededEventArgs e)
{
dgvOferty.ClearSelection();
int rowSelected = e.RowIndex;
if (e.RowIndex != -1)
{
this.dgvOferty.Rows[rowSelected].Selected = true;
}
e.ContextMenuStrip = cmstrip;
}
TADA :D. The easiest way period. For custom cells just modify a little.
It's much more easier to add only the event for mousedown:
private void MyDataGridView_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Right)
{
var hti = MyDataGridView.HitTest(e.X, e.Y);
MyDataGridView.Rows[hti.RowIndex].Selected = true;
MyDataGridView.Rows.RemoveAt(rowToDelete);
MyDataGridView.ClearSelection();
}
}
This is easier. Of cource you have to init your mousedown-event as already mentioned with:
this.MyDataGridView.MouseDown += new System.Windows.Forms.MouseEventHandler(this.MyDataGridView_MouseDown);
in your constructor.
All the answers posed in to this question are based on a mouse click event. You can also assign a ContenxtMenuStrip to your DataGridview and check if there is a row selected when the user RightMouseButtons on the DataGridView and decide whether you want to view the ContenxtMenuStrip or not. You can do so by setting the CancelEventArgs.Cancel value in the the Opening event of the ContextMenuStrip
private void MyContextMenuStrip_Opening(object sender, CancelEventArgs e)
{
//Only show ContextMenuStrip when there is 1 row selected.
if (MyDataGridView.SelectedRows.Count != 1) e.Cancel = true;
}
But if you have several context menu strips, with each containing different options, depending on the selection, I would go for a mouse-click-approach myself as well.
base on #Data-Base answer it will not work until make selection mode FullRow
MyDataGridView.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
but if you need to make it work in CellSelect Mode
MyDataGridView.SelectionMode = DataGridViewSelectionMode.CellSelect;
// for cell selection
private void MyDataGridView_MouseDown(object sender, MouseEventArgs e)
{
if(e.Button == MouseButtons.Right)
{
var hit = MyDataGridView.HitTest(e.X, e.Y);
MyDataGridView.ClearSelection();
// cell selection
MyDataGridView[hit.ColumnIndex,hit.RowIndex].Selected = true;
}
}
private void DeleteRow_Click(object sender, EventArgs e)
{
int rowToDelete = MyDataGridView.Rows.GetFirstRow(DataGridViewElementStates.Selected);
MyDataGridView.Rows.RemoveAt(rowToDelete);
MyDataGridView.ClearSelection();
}
private void MyDataGridView_MouseDown(object sender, MouseEventArgs e)
{
if(e.Button == MouseButtons.Right)
{
MyDataGridView.ClearSelection();
MyDataGridView.Rows[e.RowIndex].Selected = true;
}
}
private void DeleteRow_Click(object sender, EventArgs e)
{
Int32 rowToDelete = MyrDataGridView.Rows.GetFirstRow(DataGridViewElementStates.Selected);
MyDataGridView.Rows.RemoveAt(rowToDelete);
MyDataGridView.ClearSelection();
}
private void dataGridView1_CellContextMenuStripNeeded(object sender,
DataGridViewCellContextMenuStripNeededEventArgs e)
{
if (e.RowIndex != -1)
{
dataGridView1.ClearSelection();
this.dataGridView1.Rows[e.RowIndex].Selected = true;
e.ContextMenuStrip = contextMenuStrip1;
}
}
It is work for me without any errors:
this.dataGridView2.MouseDown += new System.Windows.Forms.MouseEventHandler(this.MyDataGridView_MouseDown);
this.dataGridView2.Click += new System.EventHandler(this.DeleteRow_Click);
And this
private void MyDataGridView_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Right)
{
var hti = dataGridView2.HitTest(e.X, e.Y);
dataGridView2.ClearSelection();
dataGridView2.Rows[hti.RowIndex].Selected = true;
}
}
private void DeleteRow_Click(object sender, EventArgs e)
{
Int32 rowToDelete = dataGridView2.Rows.GetFirstRow(DataGridViewElementStates.Selected);
if (rowToDelete == -1) { }
else
{
dataGridView2.Rows.RemoveAt(rowToDelete);
dataGridView2.ClearSelection();
}
}
You can also make this a little simpler by using the following inside the event code:
private void MyDataGridView_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Right)
{
rowToDelete = e.RowIndex;
MyDataGridView.Rows.RemoveAt(rowToDelete);
MyDataGridView.ClearSelection();
}
}
See here it can be done using the DataGridView RowTemplate property.
Note: This code isn't tested but I've used this method before.
// Create DataGridView
DataGridView gridView = new DataGridView();
gridView.AutoGenerateColumns = false;
gridView.Columns.Add("Col", "Col");
// Create ContextMenu and set event
ContextMenuStrip cMenu = new ContextMenuStrip();
ToolStripItem mItem = cMenu.Items.Add("Delete");
mItem.Click += (o, e) => { /* Do Something */ };
// This makes all rows added to the datagridview use the same context menu
DataGridViewRow defaultRow = new DataGridViewRow();
defaultRow.ContextMenuStrip = cMenu;
And there you go, as easy as that!
I have a new workaround to come in same result, but, with less code.
for Winforms... That's example is in portuguese
Follow up step by step
Create a contextMenuStrip in your form and create one item
Sign one event click (OnCancelarItem_Click) for this contextMenuStrip
Create a event 'UserDeletingRow' on gridview
and now... you've simulating on key press del from user
you don't forget to enable delete on the gridview, right?!
and finally...

Categories