2013-06-21 161 views
4

我有一個DataGridView。我在DataGridView的第4列中右鍵單擊單元格時創建了一個ContextMenuStrip。然而,我被卡住了,因爲在左鍵單擊ContextMenuStrip菜單項時,我想從右鍵單元格中提取數據。C#DataGridView右鍵單擊上下文菜單單擊檢索單元格值

我想要的單元格是ContextMenuStrip的左上角,這正是我右鍵單擊並指向想要抓取的數據的單元格的位置。 The screen grab just doesn't show the mouse cursor.

這是我到目前爲止有:

GridView1.MouseDown += new MouseEventHandler(this.dataGridView_MouseDown); 

private void dataGridView_MouseDown(object sender, MouseEventArgs e) 
    { 

     if (e.Button == MouseButtons.Right) 
     { 
      var ht = dataGridView1.HitTest(e.X, e.Y); 

      //Checks for correct column index 
      if (ht.ColumnIndex == 4 && ht.RowIndex != -1) 
      { 
       //Create the ContextStripMenu for Creating the PO Sub Form 
       ContextMenuStrip Menu = new ContextMenuStrip(); 
       ToolStripMenuItem MenuOpenPO = new ToolStripMenuItem("Open PO"); 
       MenuOpenPO.MouseDown += new MouseEventHandler(MenuOpenPO_Click); 
       Menu.Items.AddRange(new ToolStripItem[] { MenuOpenPO }); 

       //Assign created context menu strip to the DataGridView 
       dataGridView1.ContextMenuStrip = Menu; 
      } 

      else 
       dataGridView1.ContextMenuStrip = null; 
     } 
    } 

I think this post may be what I am looking for

但是,如果我改變:private void dataGridView_MouseDown(object sender, MouseEventArgs e)

private void dataGridView_MouseDown(object sender, DataGridViewCellMouseEventArgs e)

我不知道如何改變GridView1.MouseDown += new MouseEventHandler(this.dataGridView_MouseDown);所以我沒有收到錯誤消息。還是有更好的方法來做到這一點?

最終解決的幫助從Gjeltema

dataGridView1.CellMouseDown += this.dataGridView1_CellMouseDown;

private void dataGridView1_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e) 
    { 
     //Checks for correct column index 
     if (e.Button == MouseButtons.Right && e.ColumnIndex == 4 && e.RowIndex != -1) 
     { 
      //Create the ContextStripMenu for Creating the PO Sub Form 
      ContextMenuStrip Menu = new ContextMenuStrip(); 
      ToolStripMenuItem MenuOpenPO = new ToolStripMenuItem("Open PO"); 
      MenuOpenPO.MouseDown += new MouseEventHandler(MenuOpenPO_Click); 
      Menu.Items.AddRange(new ToolStripItem[] { MenuOpenPO }); 

      //Assign created context menu strip to the DataGridView 
      dataGridView1.ContextMenuStrip = Menu; 
      CellValue = dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString(); 
     } 

     else 
      dataGridView1.ContextMenuStrip = null; 
    } 

回答

1

如果你與該職位的解決方案去,然後注意,他訂閱了CellMouseDown事件,而不是MouseDown事件。這有一個不同的簽名。

而且,NET 2.0的,你並不需要所有的委託包裝的語法,你可以+=相匹配的事件委託的簽名,像這樣的功能:

// Your updated MouseDown handler function with DataGridViewCellMouseEventArgs 
GridView1.CellMouseDown += this.dataGridView_MouseDown; 

然後你將不會有錯誤消息,並可以執行您在帖子中看到的內容。

+0

謝謝!我仍然試圖圍繞着事件和代表。你的解決方案爲我工作,並改變了幾行後,我可以在單擊上下文菜單後獲取單元格值。 – Matt

相關問題