dataGridView上下文菜单函数
本文关键字:函数 菜单 上下文 dataGridView | 更新日期: 2023-09-27 18:19:43
我已经将以下代码添加到我的论坛:
private void dataGridView1_MouseClick(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Right)
{
ContextMenu a = new ContextMenu();
a.MenuItems.Add(new MenuItem("Google"));
a.MenuItems.Add(new MenuItem("Yahoo"));
int currentMouseOverRow = dataGridView1.HitTest(e.X, e.Y).RowIndex;
if (currentMouseOverRow >= 0)
{
a.MenuItems.Add(new MenuItem(string.Format("", currentMouseOverRow.ToString())));
}
a.Show(dataGridView1, new Point(e.X, e.Y));
}
}
private void dataGridView1_CellMouseEnter(object sender, DataGridViewCellEventArgs e)
{
currentMouseOverRow = e.RowIndex;
}
private void dataGridView1_CellMouseLeave(object sender, DataGridViewCellEventArgs e)
{
currentMouseOverRow = -1;
}
但是,如何将该函数添加到上下文菜单选项中呢?
对于谷歌,
Process.Start("https://www.google.com");
对于雅虎,
Process.Start("https://www.yahoo.com");
等等。
为什么不在表单loads
时添加ContextMenu
权限,而不是每次用户右键单击DataGridView
时,也就是说,每次用户右击DatGridView
时,都必须添加Context Menu
。
其次,用DataGridView
代替ContextMenu
制作一个更适合家庭使用的ContextMenuStrip
。所以,你的代码看起来像:
ContextMenuStrip a = new ContextMenuStrip();
public Form1()
{
InitializeComponent();
this.Load += new EventHandler(Form1_Load);
}
void Form1_Load(object sender, EventArgs e)
{
Image img = null;
a.Items.Add("Google", img, new System.EventHandler(ContextMenuClick));
a.Items.Add("Yahoo", img, new System.EventHandler(ContextMenuClick));
dataGridView1.ContextMenuStrip = a;
}
那么你的EventHandler
会是这样的:
private void ContextMenuClick(Object sender, System.EventArgs e)
{
switch (sender.ToString().Trim())
{
case "Google":
Process.Start("https://www.google.com");
break;
case "Yahoo":
Process.Start("https://www.yahoo.com");
break;
}
}
你的DataGridView
Mouse Click
处理程序会是这样的:
void dataGridView1_MouseClick(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Right)
{
int currentMouseOverRow = dataGridView1.HitTest(e.X, e.Y).RowIndex;
if (currentMouseOverRow >= 0)
{
a.Items.Add(string.Format("", currentMouseOverRow.ToString()));
}
a.Show(dataGridView1, new Point(e.X, e.Y));
}
}
菜单项必须使用ClickEvent
:
//menu items constructor
a.MenuItems.Add(new MenuItem("Google", new System.EventHandler(this.MenuItemClick)));
a.MenuItems.Add(new MenuItem("Yahoo", new System.EventHandler(this.MenuItemClick)));
private void MenuItemClick(Object sender, System.EventArgs e)
{
var m = (MenuItem)sender;
if (m.Text == "Google")
{
Process.Start("https://www.google.com");
}
}