C# 如何在特定DataGridViewCell中添加ContextMenu?(C)表格
我试图在DataGridView的特定单元格中添加ContextMenu。如下图所示: 我发现这很难做到,但我在TextBox控件中使用以下代码进行了一次尝试:C# 如何在特定DataGridViewCell中添加ContextMenu?(C)表格,c#,C#,我试图在DataGridView的特定单元格中添加ContextMenu。如下图所示: 我发现这很难做到,但我在TextBox控件中使用以下代码进行了一次尝试: private void Form1_Load(object sender, EventArgs e) { foreach (Control control in this.Controls) { // Add KeyDown event to each control in the form.
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);
}
但我认为ContextMenu在其第一个参数上只接受控件类型,我得到了一个例外:
cannot convert from 'System.Windows.Forms.DataGridViewCell' to 'System.Windows.Forms.Control'
这方面有什么解决办法吗?请告诉我该怎么办。。提前感谢。不要使用单元格打开菜单,而是将一个对gridview的引用传递给它,并根据gridview设置单元格的相对坐标。附加到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
}
}
与您的问题无关,但如果ctrl是DataGridView,则应该编写ctrl.GetType==typeOfDataGridView,而不是ctrl.GetType==typeOfDataGridView。我不知道这个。。。谢谢