Finding position of a cell in a datagridview

D

daveh551

I have spent hours exploring the ObjectBrowser tree trying to figure
out an answer to this:

How can I find the X-Y position of a particular cell (or at least
column, which would do for my purposes) within a DataGridView?
Especially if the grid is scrolled horizontally.

What I am trying to do is put a header above the grid over a group of
columns - much as I would get in Excel if I did a Merge Cell on, say
A1-C1, and put a group header there, and then column headers in A2,
B2, and C2. But in order to do that, I need to know the x co-ordinate
(either within the grid or within the form) of the right edge of the
3rd column. And if the grid is scrolled, then I need to be able to
figure out where that edge ends up.

If it weren't for the scrolling, I could at least start at the left
column and sum the widths of all the included columns to get the right
edge of the last column of interest. But
a) that won't include the width of any cell borders, so I'll have to
account for that separately,
b) as noted, it won't account for scrolling, and
c) there's gotta be a better way.

I tried cell.GetContentBounds(), but that appears to return the bounds
of the content within the cell, or at least something other than what
I wanted.

Any other suggestions? (Or a different approach to do what I want?)

Thanks for your help.
 
M

Morten Wennevik [C# MVP]

Hi Dave,

If you only need to know where the columns start you could monitor the
DataGridView.Scroll event and ajust a set of labels accordingly. If you put
the labels in a panel with the same width as the DataGridView the labels
would scroll as if they were part of the DataGridView.

void dataGridView1_Scroll(object sender, ScrollEventArgs e)
{
if (e.ScrollOrientation == ScrollOrientation.HorizontalScroll)
{
label1.Left = 42 - e.NewValue;
label2.Left = label1.Right;
label3.Left = label2.Right;
}
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top