2010-09-13 33 views
0

我試圖在DataGridView的特定單元格中添加ContextMenu。像下面的圖片:如何在特定的DataGridViewCell中添加ContextMenu? (C#winforms)

alt text

我發現這很難做到,但我用下面的代碼做了它在一個TextBox控件:

private void Form1_Load(object sender, EventArgs e) 
{ 
    foreach (Control control in this.Controls) 
    { 
     // Add KeyDown event to each control in the form. 
     control.KeyDown += new KeyEventHandler(control_KeyDown);    
    } 
} 

private void control_KeyDown(object sender, KeyEventArgs e) 
{ 
    Control ctrl = (Control)sender; 
    if (e.KeyData == Keys.F1) // Check if F1 is being pressed. 
    { 
     if (ctrl.GetType() == typeOf(TextBox)) // Check if the control is a TextBox 
     { 
      ToolStripControlHost lblInfo; 
      label1.Text = "This context menu is for TextBoxes."; 
      lblInfo = new ToolStripControlHost(label1); // some Label 
      contextMenuStrip1.Items.Add(lblInfo); 
      contextMenuStrip1.Show(ctrl, 0, 25); // Popups the contextMenu just below the textBox control. 
     } 
    } 
} 

我只是不知道如何在DataGridView的特定單元中執行此操作。 我試圖嘗試這個代碼:

if (ctrl.GetType() == typeOf(DataGridView)) // Check if the control is a DataGridView 
{ 
    DataGridViewCell testCell = dataGridView1[dataGridView1.CurrentCell.ColumnIndex, dataGridView1.CurrentRow.Index]; // Returns DataGridViewCell type 

    ToolStripControlHost lblInfo; 
    label1.Text = "test"; 
    lblInfo = new ToolStripControlHost(label1); // some Label 
    contextMenuStrip1.Items.Add(lblInfo); 
    contextMenuStrip1.Show(testCell, 0, 25); 
} 

但我認爲文本菜單隻接受在它的第一個參數Control類型,我得到這個異常:

cannot convert from 'System.Windows.Forms.DataGridViewCell' to 'System.Windows.Forms.Control' 

是否有這個什麼解決辦法?請告訴我該怎麼做..提前致謝。

+0

無關你的問題,但不是'如果(ctrl.GetType()== typeof運算(DataGridView中))'你應該寫'如果(Ctrl爲DataGridView中)' 。 – Timwi 2010-09-13 01:31:44

+0

我不知道這個......謝謝。 – yonan2236 2010-09-13 02:23:43

回答

0

附上DataGridView的MouseDown事件

private void _dgwMain_MouseDown(object sender, MouseEventArgs e) 
{ 
    if (e.Button == MouseButtons.Right) 
    { 
     DataGridView.HitTestInfo info = _dgwMain.HitTest(e.X, e.Y); 
     //now you can use info.RowIndex and info.CellIndex (not sure for porporty   
     //name) to generate menu you want 
    } 
} 
0

而不是使用單元格打開菜單,將它傳遞給gridview的引用,並根據gridview設置單元格的相對座標。

+0

謝謝....好主意:) – yonan2236 2010-09-15 06:49:52

相關問題