How to: Add Tables and Columns to the Windows Forms DataGrid Control
Thecontrol replaces and adds functionality to the control; however, the DataGrid control is retained for both backward compatibility and future use, if you choose. For more information, see .
You can display data in the Windows Forms DataGrid control in tables and columns by creating DataGridTableStyle objects and adding them to the GridTableStylesCollection object, which is accessed through the DataGrid control's TableStyles property. Each table style displays the contents of whatever data table is specified in the DataGridTableStyle object's MappingName property. By default, a table style with no column styles specified will display all the columns within that data table. You can restrict which columns from the table appear by adding DataGridColumnStyle objects to the GridColumnStylesCollection object, which is accessed through the GridColumnStyles property of each DataGridTableStyle object.
To add a table and column to a DataGrid programmatically
In order to display data in the table, you must first bind the DataGrid control to a dataset. For more information, see.
When programmatically specifying column styles, always create DataGridColumnStyle objects and add them to the GridColumnStylesCollection object before adding DataGridTableStyle objects to the GridTableStylesCollection object. When you add an empty DataGridTableStyle object to the collection, DataGridColumnStyle objects are automatically generated for you. Consequently, an exception will be thrown if you try to add new DataGridColumnStyle objects with duplicate MappingName values to the GridColumnStylesCollection object.
Declare a new table style and set its mapping name.
Declare a new column style and set its mapping name and other properties.
Dim myDataCol As New DataGridBoolColumn() myDataCol.HeaderText = "My New Column" myDataCol.MappingName = "Current"
DataGridBoolColumn myDataCol = new DataGridBoolColumn(); myDataCol.HeaderText = "My New Column"; myDataCol.MappingName = "Current";
Call the Add method of the GridColumnStylesCollection object to add the column to the table style
Call the Add method of the GridTableStylesCollection object to add the table style to the data grid.