简体   繁体   English

在C#datagridview中隐藏某些列标题

[英]Hidden certain column header in C# datagridview

for example if I want to make certain column header hidden in Datagridview. 例如,如果我想在Datagridview中隐藏某些列标题。 I'll use this code: 我将使用此代码:

dataGridView1.ColumnHeadersVisible = false;

But this will make all the column header to be invisible. 但这会使所有列标题都不可见。 Now what if I want only certain column header to be hidden. 如果我只想隐藏某些列标题,那该怎么办呢?

For instance I have 3 column header. 例如,我有3列标题。 I just want the 3rd column header to be invisible without hidden all the rows data belongs to that column. 我只是希望第3列标题不可见而不隐藏数据属于该列的所有行。 Is that possible? 那可能吗?

Please advise and correct me if I'm wrong. 如果我错了,请告知并纠正我。

You will need to handle the DataGridView.CellPainting Event . 您将需要处理DataGridView.CellPainting事件

In the event handler you will be given an instance of DataGridViewCellPaintingEventArgs . 在事件处理程序中,您将获得DataGridViewCellPaintingEventArgs的实例。 You can use the ColumnIndex and RowIndex properties of this object to determine if a header cell you want to hide is being painted. 您可以使用此对象的ColumnIndexRowIndex属性来确定是否正在绘制要隐藏的标题单元格。 RowIndex will be -1 if the cell being painted is a column header. 如果正在绘制的单元格是列标题,则RowIndex将为-1。

It may just be a simple matter of doing nothing except e.Handled = true; 除了e.Handled = true;之外,它可能只是一件简单的事情e.Handled = true; when the header cell in question is being painted. 当正在绘制有问题的标题单元格时。

I found this post searching for help with a similar problem. 我发现这篇文章在寻找类似问题的帮助。 I was hiding specific columns (anything past column 5) in my grid from the RowDataBound event handler using: 我使用以下命令从RowDataBound事件处理程序中隐藏我的网格中的特定列(任何超过第5列的内容):

for (int i = 6; i<e.Row.Cells.Count; i++)
{
    e.Row.Cells[i].Visible = false;
}

...which worked, but all the headers for those columns were still there. ...哪个有效,但这些列的所有标题仍然存在。 I was able to solve that by adding this line to the loop: 我能够通过在循环中添加这一行来解决这个问题:

for (int i = 6; i<e.Row.Cells.Count; i++)
{
    e.Row.Cells[i].Visible = false;
    GridView1.HeaderRow.Cells[i].Visible = false;
}

Now the columns and headers are in sync. 现在列和标题是同步的。 I'm not excited that I had to reference the GridView1 itself in the event handler, so if someone knows of a way to improve that, please go ahead. 我不是很兴奋我必须在事件处理程序中引用GridView1本身,所以如果有人知道改进它的方法,请继续。

I was eliminating everything after column 5, but you could use the same concept to hide any specific column/header. 我在第5列之后删除了所有内容,但您可以使用相同的概念来隐藏任何特定的列/标题。 Hope that helps. 希望有所帮助。

Just set the HeaderText of that column to the blank string. 只需将该列的HeaderText设置为空字符串即可。

Example: You want to hide the first column header: 示例:您想要隐藏第一个列标题:

myGridView.Columns[0].HeaderText = "";

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

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