/// <summary>
/// 根据鼠标Y坐标取得行号
/// </summary>
/// <param name="mouseLocation_Y">鼠标Y坐标</param>
/// <param name="userView">DataGridView</param>
/// <returns>鼠标所在行号</returns>
public static int GetRowIndexAt(int mouseLocation_Y, System.Windows.Forms.DataGridView userView)
{
int rowIndex = -1;
int rowOffset = 0;
int gridWidth = 1;
int padding = 1;
if (userView.ColumnHeadersVisible)
{
rowOffset += userView.ColumnHeadersHeight;
padding = 0;
}
if (rowOffset + padding < mouseLocation_Y) // 超过表列头的范围(不含顶头的边框)
{
int curRow = userView.FirstDisplayedScrollingRowIndex;
if (curRow >= 0)
{
for (int k = 0; k <= userView.DisplayedRowCount(true); k++)
{
if (curRow >= userView.Rows.Count)
{
break;
}
if (userView.Rows[curRow].Visible)
{
rowOffset += userView.Rows[curRow].Height;
}
if (rowOffset + padding + gridWidth > mouseLocation_Y) // y为当前边框位置
{
rowIndex = curRow;
break;
}
curRow++;
}
}
else
{
return rowIndex;
}
}
return rowIndex;
}