Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I add or remove columns from a Data Grid View dynamically

Tags:

c#

winforms

I have a DataGridView form in my .NET application and I'd like to be able to show or hide additional columns based on a Boolean value at run time.

What's the best way to show/hide these columns in code (as opposed to in the Forms Designer)?

like image 733
Lawrence Johnston Avatar asked May 20 '26 12:05

Lawrence Johnston


2 Answers

The easiest option (if the columns are known ahead of time) is to add them as you would normally, then set Visible as appropriate (on each) at runtime.

You can also add extra columns completely at runtime (if you can't predict the schema) - but note that this might work differently depending on whether you are using data-binding (i.e. a DataSource).

like image 119
Marc Gravell Avatar answered May 23 '26 02:05

Marc Gravell


DataGridView contains a property Columns, which is a DataGridViewColumnCollection.

I believe in this collection, you can set which columns exist, and if they are visible.

For more info, start here: http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridview.columns.aspx

like image 41
abelenky Avatar answered May 23 '26 00:05

abelenky