简体   繁体   中英

c# datagridview how to align a TextBox over the header

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

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);
}   

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM