Datagridview 上下文菜单
我想给datagridview添加一个上下文菜单(ContextMenuStrip),可以冻结,隐藏或者显示一些列。我想要的效果是只有右击列头时才弹出上下文菜单,并能真正按要求对右击时所在的列进行操作。我现在遇到的问题有:1、目前的效果是只要在datagridview中右击都会显示上下文菜单,不能实现只有在右击时才显示上下文菜单;2、执行的列索引是当前活动索引(currentCell),不是我右击时所在的列。求大神指导指导。
private void contextMenuStrip1_Opening(object sender, CancelEventArgs e) { //如果点击无效区域,返回,不弹出菜单 Point gdvPoint = this.dataGridView1.PointToScreen(new Point(0, 0)); int totalWidth = 0; foreach (DataGridViewColumn col in this.dataGridView1.Columns) { totalWidth += col.Width; } if (totalWidth > this.dataGridView1.Width - this.dataGridView1.RowHeadersWidth) { totalWidth = this.dataGridView1.Width - this.dataGridView1.RowHeadersWidth; } if (MousePosition.X < gdvPoint.X + this.dataGridView1.RowHeadersWidth || MousePosition.X > (gdvPoint.X + this.dataGridView1.RowHeadersWidth + totalWidth) || MousePosition.Y < gdvPoint.Y || MousePosition.Y > (gdvPoint.Y + this.dataGridView1.ColumnHeadersHeight)) { e.Cancel = true; } }
Point gdvPoint = this.dataGridView1.PointToScreen(new Point(0, 0)); int clickColumnIndex = this.dataGridView1.HitTest(MousePosition.X - gdvPoint.X, MousePosition.Y - gdvPoint.Y).ColumnIndex;