Microsoft Communities

Welcome to WindowsClient.net | Sign in | Join

Here are some frequently asked questions about Windows Forms and their answers.

Windows Forms FAQs

How do I use the DataColumn.Expression property to add a computed or combined column to a DataGrid?

The idea is to load your datatable in a normal fashion. Once the datatable is loaded, you can add an additional column that is computed from the other columns in your datatable. In the sample (CS, VB), we load the CustomerID, CompanyName, ContactName and ContactTitle from the Customers table in the NorthWind database. We then add an additional column that concatenates the ContactName and ContactTitle into one column.

To add the additional column, we create a DataColumn, set a mapping name, and then use the Expression property to define how the column is to be computed.

DataColumn dc = new DataColumn("Contact", typeof(string));
dc.Expression = "ContactName + ':' +ContactTitle";
_dataSet.Tables["customers"].Columns.Add(dc);

The sample actually shows two DataGrids. The first one uses the default binding to display the entire table including our added column. In the second DataGrid, we add a custom DataGridTableStyle to only display the CustomerID, CompanyName and our added column.

Contributed from George Shepherd's Windows Forms FAQ



Page view counter