Manipulating the default columns of a WinForms DataGrid
Posted: (EET/GMT+2)
Assume you have a .NET Windows Forms application and you want to display the results of a SQL query on a data grid (System.Windows.Forms.DataGrid). This is easy with C# or Delphi once you know how to use those connection, command and data adapter components. But, soon you will want to edit the columns of the data grid. Unlike in the ASP.NET world, there isn't a Columns property that you could simply modify. What to do?
Initially, a data grid doesn't contain any columns. But once you assign a data source to the DataSource property of the grid, the default columns (based on the data source) get generated. How would you change for example the widths (or other properties) of these columns?
The solution can be found by examining the data grid table styles. The WinForms DataGrid component has a public property called TableStyles, which is a collection of assigned styles to the grid. The objects in the collection in turn have a GridColumnStyles property, which is again a collection object. This is how you access the column objects.
But take note. Unless you create a table style manually to your grid, you cannot access the default columns. To create this style, you can either write code, or use the table style editor available in both Visual Studio .NET and Delphi.
When you create a default style for the grid, you don't need to generate any columns -- these will be generated automatically when you assign a data source to the grid ("bind the grid"). After binding the grid to a data source, you could simply set the column widths with code like this:
DefaultDataGridTableStyle.GridColumnStyles[0].Width := 65; { customer no }
DefaultDataGridTableStyle.GridColumnStyles[2].Width := 300; { name }
DefaultDataGridTableStyle.GridColumnStyles[3].Width := 70; { city }
Here, DefaultDataGridTableStyle is a class of type System.Windows.Forms.DataGridTableStyle. It is generated something like this when you use the designer:
Self.DefaultDataGridTableStyle.DataGrid := Self.DataGrid1; Self.DefaultDataGridTableStyle.HeaderForeColor := System.Drawing.SystemColors.ControlText; Self.DefaultDataGridTableStyle.MappingName := 'Customers'; Self.DefaultDataGridTableStyle.PreferredColumnWidth := 60;
Note the setting of the MappingName property. This is an important property, and must match the data table name of the underlying DataSet. For a DataSet, the DataMember property of the grid is the name of the internal DataTable you want to show. However if you bind the grid to a DataTable or a DataView, the DataMember property is an empty string. Even so, the MappingName property of the table style must still match the original name of the table inside the DataSet. Otherwise, the above code won't work.