Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine cell location in DataGridView

Tags:

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.

like image 508
Maxim Gershkovich Avatar asked May 09 '11 12:05

Maxim Gershkovich


1 Answers

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:

like image 165
Jay Riggs Avatar answered Sep 28 '22 12:09

Jay Riggs