How to select displayed columns in datagrid
-
24-05-2021 - |
سؤال
I'm working on a .NET Compact Framework 3.5 app that includes a DataGrid. I've created a BindingSource using the designer and added the bindingsource as the source of the datagrid. It automatically created columns for every suitable property of my source object type, but I don't want to display all the properties.
How do I specify which columns to display and which ones to hide? I tried playing around with the TableStyles property of the datagrid (both in code and in designer), didn't seem to have any effect.
المحلول 2
Figured it out. I had to add the following line of code in the form's constructor, right after InitializeComponent()
:
myDataGrid.TableStyles[0].MappingName = myBindingSource.GetListName(null);
Then I was able to change the datagrid's TableStyles
property in order to modify the displayed columns as I please.
نصائح أخرى
That didn't work for me as the TableStyles
collection of the DataGrid
control was empty at the point you specify and remains so until a DataGridTableStyle
collection is added.
Using your suggestion for setting the correct value for the MappingName
property, I achieved the desired result by creating and adding a new DataGridTableStyle
object containing only the public fields that were required in the DataGrid
.
// Create a DataGridTableStyle to hold all the columns to be displayed in the DataGrid
DataGridTableStyle myTableStyle = new DataGridTableStyle();
myTableStyle.MappingName = myBindingSource.GetListName(null); // This is the magic line
myTableStyle.GridColumnStyles.Clear();
// Add some DataGridColumnStyles
DataGridTextBoxColumn columnRowId = new DataGridTextBoxColumn();
columnRowId.MappingName = "idx"; //This must match the name of the public property
ColumnRowId.HeaderText = "Record";
tableStyleReportsSummary.GridColumnStyles.Add(columnRowId);
// Add the table style to the DataGrid
myDataGrid.TableStyles.Clear();
myDataGrid.TableStyles.Add(myTableStyle);