DataGridView ID Column Will Not Hide
Asked Answered
G

12

17

I have a DataGridView bound to an ObjectDataSource some of the columns are hidden including the ID column. The problem is that the ID column shows up even when its visible property is set to false. Has anyone run into this problem before? Setting the width to zero is not an option since the grid doesn't allow columns with a width less than 5 pixels wide so it still shows the column on the grid no matter what.

The strange thing is that the ID column wasn't always showing. After I worked on the app for a bit the columns appeared again.

DataGridView is not set to auto generate columns. I am building to version 4.0 of .NET and C#.

Here is the code in the form constructor.

dgvActiveMiners.AutoGenerateColumns = false;
dgvAvilableMiners.AutoGenerateColumns = false;
dgvOperationResults.AutoGenerateColumns = false;

dgvActiveMiners.Columns["dgvActiveMinersRecordId"].Visible = false;
dgvAvilableMiners.Columns["dgvAvilableMinersRecordId"].Visible = false;
dgvOperationResults.Columns["dgvOperationResultRecordId"].Visible = false;

This is the generated code for the grids.

this.dgvOperationResults.AllowUserToAddRows = false;
this.dgvOperationResults.AllowUserToDeleteRows = false;
this.dgvOperationResults.AutoGenerateColumns = false;
this.dgvOperationResults.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
this.dgvOperationResults.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] {
this.dgvOperationResultRecordId,
this.nameDataGridViewTextBoxColumn2,
this.typeIdDataGridViewTextBoxColumn,
this.amountDataGridViewTextBoxColumn,
this.operationIdDataGridViewTextBoxColumn});
this.dgvOperationResults.DataSource = this.operationResultBindingSource;
this.dgvOperationResults.Location = new System.Drawing.Point(12, 40);
this.dgvOperationResults.MultiSelect = false;
this.dgvOperationResults.Name = "dgvOperationResults";
this.dgvOperationResults.ReadOnly = true;
this.dgvOperationResults.Size = new System.Drawing.Size(498, 247);
this.dgvOperationResults.TabIndex = 16;

I don't know what else I could be missing?

Thanks!

Galwegian answered 15/6, 2011 at 14:22 Comment(1)
Is your data grid view set for auto-generating of columns?, Which version C# are you building with too?Carycaryatid
T
19

Suggestion 1:
Try explicitly setting the DGV Column's Visible property to false in the FormLoad event:

dataGridView.Columns["YourIdColumn"].Visible = false;

Suggestion 2:
Try changing your column dgvActiveMinersRecordId from the first column in the DGV to the last column.

Tyndale answered 15/6, 2011 at 19:18 Comment(4)
I'm not going to down vote you, but didn't the OP specifically state he'd tried this and it didn't work? (2nd sentence)Stillmann
@jp2code The OP stated he set the Visible property but I'm assuming he did so in the Winform designer and not programmatically.Tyndale
@Galwegian I've never seen the problem you're experiencing and I imagine it is quite frustrating. My answer came from a quick search where other people reported the problem, but they were using Visual Studio 2005. I know you're not using that version. I updated my answer with another suggestion that helped other people.Tyndale
Suggestion 2 is the way to go! - Have the columns you want hidden at the end. I changed my SQL query to return the IDs to hide as the last columns instead of the 1st. Who'd have thought it? Thanks a lot.Thievish
T
12

To try and answer this a bit more generically for the next person who comes along, like me...

This does seem to be a bug, but the work around is to:

Make sure the columns you want to hide are displayed last

This will depend on your code, but for some this will be:

  • SQL code changed to return the columns later
  • Change the code that adds the datagridview columns putting the "to hide" columns at the end
  • Setting the Columns[x].DisplayIndex such that the columns appear last, as per @Steve's post
Thievish answered 15/2, 2013 at 21:1 Comment(3)
Yes indeed, it seems I was only unable to hide the first column, all the others were fine. So I just made sure the first column was one I wanted to see.Anfractuosity
What a bizarre "feature".Radial
This was the solution. Thanks!. It's funny how this bug is still not fixed in 2022. I guess no one works on WinForms anymore.Mf
N
5

I have the same issue.

The following line, still leaves the column visible, even though exploring the value shows it false.

dataSelected.Columns["id"].Visible = false;

I didn't have this issue, until I had set the DisplayIndex on a column

dataSelected.Columns["ipagenum"].DisplayIndex = 6;

Moving the offending columns DisplayIndex to the end, corrected this issue.

dataSelected.Columns["id"].DisplayIndex = 15;
Noctilucent answered 30/5, 2012 at 18:32 Comment(1)
Worked for me. Would be good to know why DataGridView behaves this way.Ontiveros
T
3

Maybe a bit late but I was beating myself up with the same problem, I had two separate forms with DataGridViews both bound to different DataTables. One had no problem hiding the 1st column, on the other everything I tried didn't work, until...

Note: ["newCol"] is the first (i.e. column 0) column in the data table.

This code Fails to hide column [0] (or by name ["NewRow"])

...
MyDataGridView.DataSource = MyDatatable;
MyDataGridView.Columns["NewRow"].Visible = false;   // doesn't hide (col 0)
// MyDataGridView.Columns[0].Visible = false;  <<<< this didn't work either
MyDataGridView.Columns["Changed"].Visible = false;
MyDataGridView.Columns["Active"].Visible = false;
MyDatatable.RowFilter = "[Active] = 1";
...

this code works:

...
MyDataGridView.DataSource = MyDatatable;
MyDatatable.RowFilter = "[Active] = 1";
MyDataGridView.Columns["NewRow"].Visible = false;   // YAY!! Now it hides
// MyDataGridView.Columns[0].Visible = false;       <<<< and this works too
MyDataGridView.Columns["Changed"].Visible = false;
MyDataGridView.Columns["Active"].Visible = false;
...

Spot the difference? It's Where I specify the RowFilter.

The other form doesn't have a starting RowFilter but in both forms I later change the RowFilter (depending on user actions), column 0 never comes back.

Seems specifying RowFilter too soon after hiding columns fails for column 0.

Very very weird!!!! Very very frustrating!!!!

Thamos answered 24/11, 2012 at 4:35 Comment(0)
S
1

That's odd.

Are you certain you are calling the right column name? I realize that would be a stupid mistake to make, but it happens!

Here's a simple test you could try:

void test(string columnName, bool visibility) {
  if (dataGridView1.Columns.Contains(columnName)) {
    dataGridView1.Columns[columnName].Visible = visibility;
  } else {
    throw new Exception(string.Format("Column '{0}' does not exist in DataGridView '{1}'.", columnName, dataGridView1.Name));
  }
}
Stillmann answered 15/6, 2011 at 19:34 Comment(0)
F
1

I would like to contribute a perspective that has not been mentioned.

Each column of the DataGridView has a property name. You can directly access the column by name, as you would to access any other element. For example: ColumnName.Property = AnyProperty. In your case: ColumnName.Visible = false.

I think it is cleaner, more direct, and less likely to make a mistake. We also help a bit the compiler :)

In this way, it is not necessary to use the property name of the DataGridView, neither locate the desired column mediate a string (which potentially can be commited an error). I mean this: YourDataGridView.Columns ["YourColumn"] Property = AnyProperty.

Flan answered 15/1, 2015 at 15:41 Comment(0)
R
1

The problem in my case was grid.Columns.Add(column).

This is due to a bug that has never been fixed where the first columns visibility gets reset. Thanks to the person who found this. Link to the original solution: https://mcmap.net/q/743434/-why-do-columns-not-stay-hidden-after-calling-datagridview-columns-clear. Give him an upvote if this has helped you like it did me 🙂.

How to fix:

  1. Make sure the grid is not in bound mode when repopulating columns

     var dataSource = dataGridView.DataSource;
     dataGridView.DataSource = null;
     // Repopulate columns
     //...
     dataGridView.DataSource = dataSource;
    
  2. Don't use Add method. Create all columns and keep them in either variables or temporary list, and at the end use the AddRange method which has no such effect.

  3. Do not set Visible = false in advance. Create and add all the columns, then hide the desired ones.

Rammish answered 27/2, 2024 at 7:40 Comment(0)
M
0

I had the same issue and none of the above worked for me. My fix was to set a DataPropertyName at least for the column that should be hidden in the designer at "Edit columns".

Madeup answered 1/7, 2016 at 8:53 Comment(0)
S
0

If you want to hide a column by name, you have to give a Name at your column. Initiliaze the property Name and after you can use it by code.

Strongbox answered 16/6, 2017 at 13:52 Comment(0)
B
0

I was having the same problem, and I did not want have to change the index of my id column to the visible property works. So I noticed that after I indicated that the id column visible = false, I was deleting the last row of the DataGridView and this is what was making the id column appear. So I delete the row first and then indicate that the id column = false.

Benison answered 25/6, 2018 at 13:1 Comment(0)
C
0

I have a similar problem. I added an unbound checkbox column to my data bound grid. It became the first column. When I stepped through my grid like so:

for (int i = 0; i < grvQuoteCostSheets.RowCount; i++)
{
   grvQuoteCostSheets[grcQCostSProfit.Index, i].Value
      = (Convert.ToInt32(grvQuoteCostSheets[grcQCostSPrice.Index, i].Value) - Convert.ToInt32(grvQuoteCostSheets[grcQCostSTotalCost.Index, i].Value));
}
idColumn.Visible = false;   //Need to rehide.

The first hidden column visibility switched to False. I moved the CKBox column from first to 3rd place as suggested in a different answer (the next two columns being an ID value & Line# respectively, and hidden) and the checkbox column stayed hidden. I was hiding the ID column after the math as it was flipping to Visible. I just lived with it before (hiding the ID column after the math loop), but now that I added the checkbox column, I decided to dig a bit, and here I am. I also tried doing the math in a list grabbed from the grid, and the checkbox column would still flip to Visible when the CKBox was first. I’m still stuck with the first hidden column wanting to flip to visible, so I re-hide it. I do have AutoGenerateColumns = False and am explicitly setting the first column visibility to false as well. Both to no avail.

Coagulase answered 14/10, 2020 at 15:4 Comment(0)
S
0

Don't know if anybody is still struggling with the issue. I had the same problem and was setting the visible property in the dataSourceChanged event.

When I put the visible false in the show event instead it worked.

Scherman answered 11/8, 2021 at 13:21 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.