Implement Advanced DataGrid Styles
Dig into some manual coding techniques for adding special effects to data displays.
by Fabio Claudio Ferracchiati and Juval Löwy
October 2003 Issue
Technology Toolbox: VB.NET, C#
Q: Implement Advanced DataGrid Styles
I'm developing a .NET WinForms application that uses a DataGrid to display data the app retrieves from a table in a remote database. The table has a foreign-key column, and I'd like to use a ComboBox control in the related column of the DataGrid to display data retrieved from the second table. I also want to change a cell's color when its value is less than zero. I found some information on DataGrid styles but wasn't able to implement them in my application.
A:
The DataGrid WinForms component is powerful and flexible, but implementing effects that go beyond the component's standard behavior can be difficult. You can't implement the advanced effects you want by simply setting DataGrid properties or calling DataGrid methods, and you can't delegate DataGrid style settings to the VS.NET wizard. You must specify each column manually by creating a new object from the related DataGrid column class ( download the sample code). For example, if the DataGrid column must contain a string, you create a DataGridTextBoxColumn object that specifies the data-source column to bind from. Then, you add the object to the DataGridTableStyle class's GridColumnStyles collection. Finally, you must specify the reference to the DataGridTableStyle object in the DataGrid object's TableStyles collection:
Dim styles As New DataGridTableStyle
styles.MappingName = "Authors"
Dim colAuthor As New DataGridTextBoxColumn
colAuthor.MappingName = "Author"
colAuthor.HeaderText = "Author"
colAuthor.Width = 200
styles.GridColumnStyles.Add(colAuthor)
Dim dg As new DataGrid
dg.TableStyles.Add(styles)
Use the DataGridTableStyle class's MappingName property to specify the data-source table to bind from, and the DataGrid column class's MappingName property to specify the data source's column name to bind from.
Back to top
|