上图是最佳datagridview与contextmenustrip合用效果,方法是:
而当两个以上的datagridview共同使用一个ContextMenuStrip时,【打开】【关闭】处理事件识别SourceControl的方法:
- private void 打开ToolStripMenuItem_Click(object sender, EventArgs e)
- {
- ContextMenuStrip cmStrip = (ContextMenuStrip)((ToolStripMenuItem)sender).Owner;
- string ctrlSrcName = cmStrip.SourceControl.Name;
- if (ctrlSrcName.Equals("dataGridView3"))
- {}
- else if (ctrlSrcName.Equals("dataGridView4"))
- {}
- }
附动态右键生成contextMenuStrip的方法:
- private void dataGridView4_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
- {
- if (e.Button == System.Windows.Forms.MouseButtons.Right)
- {
- if (e.RowIndex >= 0)
- {
- dataGridView4.ClearSelection();
- dataGridView4.Rows[e.RowIndex].Selected = true;
- dataGridView4.CurrentCell = dataGridView4.Rows[e.RowIndex].Cells[e.ColumnIndex];
- this.contextMenuStrip1.Tag = "dataGridView4";
- this.contextMenuStrip1.Show(MousePosition.X, MousePosition.Y);
- }
- }
- }