Live Chat Icon For mobile
Live Chat Icon

How do I use the DataColumn.Expression property to add a computed/combined column to my datagrid

Platform: WinForms| Category: 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.

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

[VB.NET]
  Dim dc As DataColumn
  dc = New DataColumn(''Contact'', GetType(System.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.

Share with

Share on twitter
Share on facebook
Share on linkedin

Related FAQs

Couldn't find the FAQs you're looking for?

Please submit your question and answer.