We use cookies to give you the best experience on our website. If you continue to browse, then you agree to our privacy policy and cookie policy.
Unfortunately, activation email could not send to your email. Please try again.
Platform : Windows Forms
|
Category : Datagrid

How can I programatically add and remove columns in my DataGrid without modifying the DataTable datasource

You can control the columns displayed in the DataGrid through the DataGrid.TableStyle[0].GridColumnStyles collection. To do so, create a DataGridTableStyle and set its MappingName property to point to the name of your DataTable which is the DataSource for the DataGrid. Next, add this DataGridTableStyle to the DataGrid.TableStyles property. Finally, set the DataGrid.DataSource property to the DataTable. Doing things in this order, guarantees that the DataGridTableStyle.GridColumnStyles collection will be fully populated showing all the DataTable columns in the the DataGrid.

Then to add and remove columns from the DataGrid, you only have to add and remove DataGridColumnStyle objects from this DataGrid.TableStyle[0].GridColumnStyles collection. Removing them is straight-forward through a Remove method call. But inserting them requires more work as there is no InsertAt method defined for this collection. To handle this problem, you can create a new array of DataGridColumnStyles, and populate this array in the necessary order to reflect the DataGrid with an inserted column. Then you can clear the old collection, and create a new collection with this new array. You really are not creating all new DataGridColumnStyle objects, but are simply reordering the existing ones in a new collection.

Here is a sample project containing both C# and VB.NET code showing how you might do this.

You are using an outdated version of Internet Explorer that may not display all features of this and other websites. Upgrade to Internet Explorer 8 or newer for a better experience.