How To Show Only a Subset of the Columns in the DataGrid
Introduction
This is a common problem: You have a table with a lot of columns and you only want to show some columns to the user in a DataGrid. Or, you have an ID column that you don't want to show the user.
Unfortunately when you set the DataSource of the Datarid to be a DataTable or a DataView, the user can see all the columns, and there is no easy way to filter what columns you actually need.
Using DataGridColumnStyles Will Solve The Problem.
You can learn about DataGridColumnStyles in this post. When you setup ColumnStyles to your DataGrid the user can see only those which where added explicitly to the TableStyle.
For example: If you have 3 columns in your DataTable: ID, Name and Value and you only want to show Name and Value. The code to use is this:
---------------------------------------
//Initialize objects
DataGridTableStyle myTable = new DataGridTableStyle();
DataGridTextBoxColumn nameColumn = new DataGridTextBoxColumn();
DataGridTextBoxColumn valueColumn = new DataGridTextBoxColumn();
//Setting a DataTable as the DataSource - dt is DataTable object
dataGrid1.BeginInit();
dataGrid1.DataSource = dt;
// myTable
dataGrid1.TableStyles.AddRange(new DataGridTableStyle[] {myTable});
myTable.DataGrid = dataGrid1;
myTable.GridColumnStyles.AddRange(new DataGridColumnStyle[] {nameColumn,valueColumn});
myTable.MappingName = "TableName"; // This is the name of the table.
// nameColumn
nameColumn.MappingName = "Name"; // This is the name of the column.
// valueColumn
valueColumn.MappingName = "Value"; // This is the name of the column.
dataGrid1.EndInit();
---------------------------------------We did not create a ColumnStyle for the Id column, so the user will not see it in the grid. Of course when creating a new row in the grid we will need a mechanism to set the Id instead of the user (for example: AutoNumber).
In the next post I will take this one step further and show how to set different views of columns.
0 Comments:
Post a Comment
<< Home