Using .NET DataGrid with Collections
-
I want to use the Windows .NET DataGrid to display items in a collection. This is quite easy dataGrid1.DataSource = myCollection; BUT the columns appear in an arbitary order (not as declared in the item class). Is there anyway to specify the order that public properties of a class are read by the data binding mechanism of the datagrid. I know that gridcolumnstyles can be used but only where tables are used. Any clues would be gratefully appreciated.
-
I want to use the Windows .NET DataGrid to display items in a collection. This is quite easy dataGrid1.DataSource = myCollection; BUT the columns appear in an arbitary order (not as declared in the item class). Is there anyway to specify the order that public properties of a class are read by the data binding mechanism of the datagrid. I know that gridcolumnstyles can be used but only where tables are used. Any clues would be gratefully appreciated.
I've used this approach many times
DataGridTableStyle gridStyle = new DataGridTableStyle(); gridStyle.ReadOnly = true; gridStyle.MappingName = myCollection.GetType().Name; DataGridTextBoxColumn cs = new DataGridTextBoxColumn(); cs.MappingName = "VehicleID"; // public property name cs.HeaderText = "Vehicle ID"; // column header cs.Alignment = HorizontalAlignment.Center; cs.Width = 80; cs.TextBox.Enabled = false; gridStyle.GridColumnStyles.Add(cs); // repeat for other properties // add style to collection dataGrid1.TableStyles.Add(gridStyle);
the column order will follow the order in which the DataGridTextboxColumns are added to the gridstyle.