DataGridViewでの右クリックメニューの作り方
画面を作り込んでいく中でDataGridViewの情報を削除するUIに悩んだ結果
コンテキストメニューに「削除」を表示する方法を試してみた。
メニューがでる位置が一定ではないのが気になるが・・・・
とりあえず↓のようなロジックで行った。
private void dgv_Keiyaku_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e)
{
// 選択行の連番号を取得して削除のキーに使う
int dgv_Keiyaku_SelectedRowNo = Int32.Parse(dgv_Keiyaku.CurrentRow.Index.ToString());
dgv_Keiyaku_SelectedSeqNo = Int32.Parse(dgv_Keiyaku[8, dgv_Keiyaku_SelectedRowNo].Value.ToString());
if (e.Button == MouseButtons.Right)
{
// マウスがクリックされた座標(e.X, e.Y)から、
ContextMenuStrip contexMenu = new ContextMenuStrip();
contexMenu.Items.Add("削除");
contexMenu.ItemClicked += new ToolStripItemClickedEventHandler(contexMenu_ItemClicked);
contexMenu.Show(dgv_Keiyaku, new Point(e.X, e.Y));
}
if (e.RowIndex != -1 && e.ColumnIndex != -1)
{
if (e.Button == MouseButtons.Right)
{
DataGridViewCell clickedCell = (sender as DataGridView).Rows[e.RowIndex].Cells[e.ColumnIndex];
// Here you can do whatever you want with the cell
this.dgv_Keiyaku.CurrentCell = clickedCell; // Select the clicked cell, for instance
// Get mouse position relative to the vehicles grid
var relativeMousePosition = dgv_Keiyaku.PointToClient(Cursor.Position);
// Show the context menu
ContextMenuStrip contexMenu = new ContextMenuStrip();
contexMenu.Show(dgv_Keiyaku, relativeMousePosition);
}
}
//if (e.Button == MouseButtons.Right)
//{
// ContextMenu m = new ContextMenu();
// m.MenuItems.Add(new MenuItem("Cut"));
// m.MenuItems.Add(new MenuItem("Copy"));
// m.MenuItems.Add(new MenuItem("Paste"));
// int currentMouseOverRow = dgv_Keiyaku.HitTest(e.X, e.Y).RowIndex;
// if (currentMouseOverRow >= 0)
// {
// m.MenuItems.Add(new MenuItem(string.Format("Do something to row {0}", currentMouseOverRow.ToString())));
// }
// Console.WriteLine("X({0}, Y({1})", e.X, e.Y);
// m.Show(dgv_Keiyaku, new Point(e.X, e.Y));
//}
}