确定DataGridView中的单元格位置 [英] Determine cell location in DataGridView

查看:149
本文介绍了确定DataGridView中的单元格位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定一个特定的行号和列索引我如何计算一个DataGridView中的单元格位置(IE:Location.Point)?



我需要位置的原因的单元格,所以我可以在单元格内放置一个按钮以允许文件夹浏览(datagridview显示文件夹路径)。



关于如何完成这一欢迎的备选建议。

解决方案

您不能真正找到DGV单元的点,因为单元格占用DGV中的矩形区域。但是,您可以使用 DataGridView找到此区域.GetCellDisplayRectangle()方法。它为单元格列和行索引给出的DGV单元格的显示区域返回一个 Rectangle 。如果您真的想要一个点,您可以轻松地使用 Rectangle 为任何 Rectangle 的四个角点。

  //获取第二列第二列矩形。 
var cellRectangle = dataGridView1.GetCellDisplayRectangle(1,1,true);
//如果需要,可以使用Rectangle创建点。
Console.WriteLine(左上角x:{0} \t y:{1},cellRectangle.Left,cellRectangle.Top);
Console.WriteLine(Bottom right x:{0} \t y:{1},cellRectangle.Right,cellRectangle.Bottom);

但我同意你的问题的评论者;最好创建一个自定义的DataGridViewColumn并在那里托管你的TextBox和Button。 这是一个为DateTimePicker控件执行此操作的示例:


Given a specific row number and column index how can I calculate the cell location (IE: Location.Point) inside a DataGridView?

The reason I need the location of the cell is so I can position a button inside the cell to allow for folder browsing (the datagridview shows folderpaths).

Alternative suggestions about how to accomplish this welcome.

解决方案

You can't really find a point for a DGV cell because cells occupy a rectangular area in a DGV. However, you can find this area by using the DataGridView.GetCellDisplayRectangle() method. It returns a Rectangle for the display area of a DGV Cell given by the Cell's column and row indices. If you really want a point you can easily use the Rectangle to construct Points for any of the Rectangle's four corners.

// Get Rectangle for second column in second row.
var cellRectangle = dataGridView1.GetCellDisplayRectangle(1, 1, true);
// Can create Points using the Rectangle if you want.
Console.WriteLine("Top Left     x:{0}\t y:{1}", cellRectangle.Left, cellRectangle.Top);
Console.WriteLine("Bottom Right x:{0}\t y:{1}", cellRectangle.Right, cellRectangle.Bottom);

But I agree with your question's commenters; it would be better to create a custom DataGridViewColumn and host your TextBox and Button there. Here's an example of doing this for the DateTimePicker control:

这篇关于确定DataGridView中的单元格位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆