I have a database that has a Users table and I present the data in a DataGridView. I would like to remove 4 columns, but the code I have (referenced from MSDN) seems to append the columns at the end. How can I totally REMOVE the columns?
So this is how the DGV looks without the columns removed
The Code I use to TRY and remove the columns
RadarServerEntities rse = new RadarServerEntities();
gvUsers.DataSource = rse.Users;
gvUsers.Columns.Remove("ID");
gvUsers.Columns.Remove("InsertDate");
gvUsers.Columns.Remove("Connections");
gvUsers.Columns.Remove("MachineID");
The result
I would like to get rid of the last 4 columns, so why isnt my code doing it?
Many Thanks :)
When your DataGridView control is set to autogenerate its columns based on data from its data source, you can selectively omit certain columns. You can do this by calling the Remove method on the Columns collection. Alternatively, you can hide columns from view by setting the Visible property to false .
To hide a column programmaticallySet the DataGridViewColumn. Visible property to false .
To add a column using the designer ) on the upper-right corner of the DataGridView control, and then select Add Column.
The DataGridView control provides a customizable table for displaying data. The DataGridView class allows customization of cells, rows, columns, and borders through the use of properties such as DefaultCellStyle, ColumnHeadersDefaultCellStyle, CellBorderStyle, and GridColor.
I tend to just hide the fields instead.
gvUsers.Columns["ID"].Visibility = false;
Et cetera.
To actually remove automatically generated column you have to turn off automatic generation after data binding.
So the code would be:
RadarServerEntities rse = new RadarServerEntities();
gvUsers.DataSource = rse.Users;
gvUsers.AutoGenerateColumns = false;
gvUsers.Columns.Remove("ID");
gvUsers.Columns.Remove("InsertDate");
gvUsers.Columns.Remove("Connections");
gvUsers.Columns.Remove("MachineID");
I haven't checked what exactly happens, but probably the moment DGV becomes visible, missing columns are re-autogenerated.
So with this solution you have columns generated at the moment of binding data, then you turn it off and remove columns that you don't need. Missing columns can't be re-generated.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With