根据鼠标点击位置获取DataGridView的选择行号。

一个非常非常郁闷的问题:在DataGridView中当右键点击某一行的时候才显示右键菜单。

找了好几个方法结果总是回归到对鼠标点击位置的判断,用鼠标点击位置来判断点中的是哪一行。

找了好几个函数都没有找到。

 1 /// <summary>
 2         /// 获取DataGridView中点击的行号
 3         /// </summary>
 4         /// <param name="mouseLocation_Y">鼠标的Y坐标</param>
 5         /// <returns>行索引</returns>
 6         public int GetRowIndexAt(int mouseLocation_Y)
 7         {
 8             if (dataGridView_Values.FirstDisplayedScrollingRowIndex < 0)
 9             {
10                 return -1;  // no rows.   
11             }
12             if (dataGridView_Values.ColumnHeadersVisible == true && mouseLocation_Y <= dataGridView_Values.ColumnHeadersHeight)
13             {
14                 return -1;
15             }
16             int index = dataGridView_Values.FirstDisplayedScrollingRowIndex;
17             int displayedCount = dataGridView_Values.DisplayedRowCount(true);
18             for (int k = 1; k <= displayedCount;)  // 因为行不能ReOrder,故只需要搜索显示的行   
19             {
20                 if (dataGridView_Values.Rows[index].Visible == true)
21                 {
22                     Rectangle rect = dataGridView_Values.GetRowDisplayRectangle(index, true);  // 取该区域的显示部分区域   
23                     if (rect.Top <= mouseLocation_Y && mouseLocation_Y < rect.Bottom)
24                     {
25                         return index;
26                     }
27                     k++;  // 只计数显示的行;   
28                 }
29                 index++;
30             }
31             return -1;
32         }

找了好久才在MSDN上看到贴出的这个函数,测试了一下是正确的。

转载于:https://www.cnblogs.com/Iamsorry/p/5110539.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值