如何在DataGridView中获取当前单元格的位置x和y?

20

我有一个包含隐藏日历的 Windows 表单。我想将该表单显示在 DataGridView 的当前单元格下方。位置会随着当前单元格的位置而改变。

我不需要当前单元格或当前列,我需要位置信息以便设置我的日期表单的位置。

以下是我正在使用的代码,但它没有起作用:

int po_X = paygrid.GetCellDisplayRectangle(e.ColumnIndex, e.RowIndex, false).Left+paygrid.Left;
int po_Y = paygrid.GetCellDisplayRectangle(e.ColumnIndex, e.RowIndex, false).Bottom+paygrid.Top;
form_date.Location = new System.Drawing.Point(po_X, po_Y);
4个回答

26
您可以使用 paygrid.PointToScreen() 方法。
form_date.Location = paygrid.PointToScreen(
   paygrid.GetCellDisplayRectangle(e.ColumnIndex, e.RowIndex, false).Location);

我不知道是谁接受了这个答案,但它并没有按照预期的方式工作... - Wolfgang Roth
哈哈,这肯定是10年前写的时候有效的。 也许你应该再问一次,并指明你使用的工具版本以及你当前实验的结果和期望。 - watbywbarif
你好,我正在使用类似这样的代码: Rectangle r = dataGridView1.GetCellDisplayRectangle(e.ColumnIndex, e.RowIndex, false); frm.Location = dataGridView1.PointToScreen(r.Location); DialogResult dr = frm.ShowDialog(this);嗯,看起来和你的一样...我在写第一个评论时可能做了些不同的事情... - Wolfgang Roth

2
你可以尝试这个方法:
Lookup_Account.Left = datagrid_setting.GetCellDisplayRectangle(colIndex, rowIndex, False).Left
Lookup_Account.Top = datagrid_setting.GetCellDisplayRectangle(colIndex, rowIndex, False).Top

1
欢迎来到StackOverflow!请给您的代码加一个简短的解释。为什么它能工作,以及如何工作? - Aurasphere

1
Rectangle cellRect = paygrid.GetCellDisplayRectangle(e.ColumnIndex, 
e.RowIndex, true);

所以您可以使用:

cellRect.X - for X position, cellRect.Y - for Y position,
cellRect.Width - for column width and cellRect.Height - for column height

0

你可以尝试一下

[DllImport("user32.dll", EntryPoint = "GetCursorPos")]
private static extern bool GetCursorPos(out Point lpPoint);

并调用方法为

Point pt;
GetCursorPos(out pt);

pt会提供x和y。


谢谢,但我不想得到光标的位置,我想要DataGridView中当前单元格的位置。而且你已经从watbywbarif那里得到了我的答案。 - user1231584

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接