简体   繁体   中英

Hidden certain column header in C# datagridview

for example if I want to make certain column header hidden in 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. I just want the 3rd column header to be invisible without hidden all the rows data belongs to that column. Is that possible?

Please advise and correct me if I'm wrong.

You will need to handle the DataGridView.CellPainting Event .

In the event handler you will be given an instance of 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. RowIndex will be -1 if the cell being painted is a column header.

It may just be a simple matter of doing nothing except 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:

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.

I was eliminating everything after column 5, but you could use the same concept to hide any specific column/header. Hope that helps.

Just set the HeaderText of that column to the blank string.

Example: You want to hide the first column header:

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

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