请教关于 DataGridView 右键菜单

chencang 2009-04-29 01:45:12
我在 WinForm 中的 DataGridView 上关联右键菜单,实现批量修改记录中的某些字段值
问题是:如何使得只有在选中2条以上记录,并在记录内容上点右键才弹出菜单,也就是说点击列头和行首不要弹出,只选中一条记录时不弹出?

呼叫高手。。。。
...全文
745 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
笑歌自若 2012-10-22
  • 打赏
  • 举报
回复
Bensson正确!+1
chencang 2009-04-29
  • 打赏
  • 举报
回复
Bensson正确,谢谢!!
Bensson 2009-04-29
  • 打赏
  • 举报
回复
this.contextMenuStrip1.Show(this.tblMtrlDetailDataGridView, e.Location); // new Point(e.X, e.Y) 也不行
替换为:
int cellX = tblMtrlDetailDataGridView.GetCellDisplayRectangle(e.ColumnIndex, e.RowIndex, true).X;
int cellY = tblMtrlDetailDataGridView.GetCellDisplayRectangle(e.ColumnIndex, e.RowIndex, true).Y;
this.contextMenuStrip1.Show(this.tblMtrlDetailDataGridView, new Point(cellX + e.X, cellY + e.Y));
happy664618843 2009-04-29
  • 打赏
  • 举报
回复
顶顶!
chencang 2009-04-29
  • 打赏
  • 举报
回复
受1楼2楼的启发,代码改为:
if (e.Button == MouseButtons.Right) // 右键
{
if (this.tblMtrlDetailDataGridView.SelectedRows.Count > 1 && e.RowIndex >= 0 && e.ColumnIndex >= 0 && tblMtrlDetailDataGridView.Rows[e.RowIndex].Selected) // 选中记录超过1条,点击非列头行首,点击被选中行
{
this.contextMenuStrip1.Show(this.tblMtrlDetailDataGridView, e.Location); // new Point(e.X, e.Y) 也不行
}
else
{
this.contextMenuStrip1.Hide();
}
}

基本成功,可惜弹出菜单定位有问题,离鼠标右击的位置差距很大

高手继续指点。。。。
songjun174 2009-04-29
  • 打赏
  • 举报
回复
判断选择的行号是0还是1或者更多
如果是0,1则不弹出对话框
否则弹出对话框
也就是所谓的右键选择
maplesept 2009-04-29
  • 打赏
  • 举报
回复
int _rowIndex=-1;//选中行的行号
private void dataGridViewAPStatus_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Right)
{
if (Source.isBatchShow == 0)
{
_rowIndex = this.dataGridView1.HitTest(e.X, e.Y).RowIndex;

int selectedCols=0;
for(int i=0;i<dataGridView1.Rows.count;i++)
{
if(this.dataGridView1.Rows[i].Cell[0].Value!=null&&(bool)this.dataGridView1.Rows[i].Cell[0].Value==true)
{
selectedCols++;
}
}
if (_rowIndex != -1&&selectedCols)
{
//显示右键菜单
this.contextMenuStrip1.Show(this.dataGridView1, new Point(e.X, e.Y));
}
}
}
}

要这样实现就不能把菜单用dataGridView1的ContextMuneStript属性了。只能获取右键事件了

另外我一般是在选中某行(第一列是复选框的选中)时就把选中的行存放到列表中,省的每次都循环耗资源

111,126

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Creator Browser
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧