我試圖在DataGridView
的特定單元格中添加ContextMenu
。像下面的圖片:如何在特定的DataGridViewCell中添加ContextMenu? (C#winforms)
我發現這很難做到,但我用下面的代碼做了它在一個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'
是否有這個什麼解決辦法?請告訴我該怎麼做..提前致謝。
無關你的問題,但不是'如果(ctrl.GetType()== typeof運算(DataGridView中))'你應該寫'如果(Ctrl爲DataGridView中)' 。 – Timwi 2010-09-13 01:31:44
我不知道這個......謝謝。 – yonan2236 2010-09-13 02:23:43