Concatenating two string columns in a DataTable

The Expression property in DataColumn object of DataTable can be used to create calculated columns.

Assume that a DataTable contain two columns First Name and Last Name of string type. Suppose that you need to create a column in a DataTable by concatenating these two existing columns, you can simply use the ‘+’ operator in the Expression property of the newly created column. It will concatenate the First Name and Last Name without any space. If you want to add a ‘-‘ operator between the First Name and Last Name, the following code will help you.


DataTable dtTest = new DataTable();
dtTest.Columns.Add("FirstName", System.Type.GetType("System.String"));
dtTest.Columns.Add("LastName", System.Type.GetType("System.String"));
DataColumn dcFullName = new DataColumn("FullName");
dcFullName.Expression = string.Format("{0}+'-'+{1}", "FirstName", "LastName");
dtTest.Columns.Add(dcFullName);

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


%d bloggers like this: