2

我已将此代码添加到我的论坛:

    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");

等等

4

2 回答 2

1

您必须使用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");
     }
}
于 2013-06-25T07:42:29.187 回答
1

为什么不在ContextMenu您的表单loads而不是每次用户右键单击您的时候添加您的权限,DataGridView这意味着您必须在Context Menu每次用户权限单击您的DatGridView.

其次,与其ContextMenu做一个ContextMenuStrip,不如用哪个更在家DataGridView。因此,您的代码如下所示:

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));
     }
 }
于 2013-06-26T04:07:18.787 回答