2013-06-25 48 views
1

我加入這個代碼,以我的論壇:的dataGridView上下文菜單功能

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

+0

你的意思是當一個ContextMenu項目被點擊說谷歌? – Edper

+0

@Edper是的,我喜歡。 –

+0

我編輯了你的標題。請參閱:「[應該在其標題中包含」標籤「](http://meta.stackexchange.com/questions/19190/)」,其中的共識是「不,他們不應該」。 –

回答

1

爲什麼不加你的ContextMenu當您的表格loads而不是每次用戶右鍵單擊您的DataGridView這意味着您必須在每次用戶權限點擊DatGridView時添加Context Menu

其次,而不是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; 
    } 
} 

而且你DataGridViewMouse 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)); 
    } 
} 
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"); 
    } 
} 
+0

當我嘗試這個時,什麼都沒有發生。 –

+0

事件是否被解僱? – gzaxx

+0

是的,它是...... –