Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove Column from DataGridView

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

Without Removal Code

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

With Removal Code

I would like to get rid of the last 4 columns, so why isnt my code doing it?

Many Thanks :)

like image 501
craig1231 Avatar asked Jan 19 '12 17:01

craig1231


People also ask

How to Remove extra column in DataGridView in c#?

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 .

How to hide Columns in DataGridView?

To hide a column programmaticallySet the DataGridViewColumn. Visible property to false .

How do I add a column to a data grid view?

To add a column using the designer ) on the upper-right corner of the DataGridView control, and then select Add Column.

What is DataGridView in C#?

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.


2 Answers

I tend to just hide the fields instead.

gvUsers.Columns["ID"].Visibility = false;

Et cetera.

like image 90
Alexander R Avatar answered Oct 08 '22 10:10

Alexander R


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.

like image 34
Soul Reaver Avatar answered Oct 08 '22 10:10

Soul Reaver