简体   繁体   English

c#datagridview如何在标题上对齐文本框

[英]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.. 我有这个问题:我需要在我的DataGridView的列标题上方放置一个TextBox才能找到它,我开始读取列的矩形以检索左侧位置和宽度。

Rectangle rec = dgv.GetColumnDisplayRectangle(mycolumnIndex, true);

and this works fine, but if the grid contains no rows, the Rectangle is 0.. 并且可以正常工作,但是如果网格不包含任何行,则Rectangle为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. 无论是否有任何行或是否有选定的行,从GetColumnDisplayRectangle返回的Rectangle对于任何可见列总是正确的。

If it is Empty for you, then your Column is either invisible or scrolled outside of the the display area. 如果对您而言为Empty ,则您的Column不可见滚动到显示区域之外。

You will need to set the location of your TextBox or whatever Control you place there, both after a ColumnWidthChanged and a Scroll event. ColumnWidthChangedScroll事件之后,都需要设置TextBox的位置或放置在此处的任何Control 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);
}   

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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