Reputation: 7993
I have this problem: I need to put a TextBox
over the column header of my DataGridView
.. to find this I start reading the rectangle of the column to retrieve the left position and the width..
Rectangle rec = dgv.GetColumnDisplayRectangle(mycolumnIndex, true);
and this works fine, but if the grid contains no rows, the Rectangle
is 0..
any ideas?
thanks
Upvotes: 1
Views: 2218
Reputation: 54433
Whether there are any rows or not or selected rows or not, the Rectangle
returned from GetColumnDisplayRectangle
is always correct for any visible column.
If it is Empty
for you, then your Column
is either invisible or scrolled outside of the the display area.
You will need to set the location of your TextBox
or whatever Control
you place there, both after a ColumnWidthChanged
and a Scroll
event. Also whenever you hide or show Columns.
Here is a working example:
private void Form1_Load(object sender, EventArgs e)
{
textBox1.Parent = dataGridView1; // nest the TextBox
placeControl(dataGridView1, textBox1, 2); // place it over the 3rd column header
}
private void dataGridView1_ColumnWidthChanged(object sender, DataGridViewColumnEventArgs e)
{
placeControl(dataGridView1, textBox1, 2);
}
private void dataGridView1_Scroll(object sender, ScrollEventArgs e)
{
placeControl(dataGridView1, textBox1, 2);
}
void placeControl(DataGridView dgv, Control ctl, int index)
{
Rectangle R = dgv.GetColumnDisplayRectangle(index, true ); // or false
ctl.Location = R.Location;
ctl.Size = new Size(R.Width, dgv.ColumnHeadersHeight);
}
Upvotes: 2