根据鼠标点击位置获取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上看到贴出的这个函数,测试了一下是正确的。

posted @ 2016-01-07 17:13  小书丶  阅读(2032)  评论(0编辑  收藏  举报