简体   繁体   中英

How to properly concatenate the values of Columns of a DataTable?

In the following code, I noticed that Columns A and B show data.
However, columns C and D are empty. Why?

DataTable _dt = new DataTable();
DataColumn A=_dt.Columns.Add("A");
DataColumn B=_dt.Columns.Add("B");
DataColumn C=_dt.Columns.Add("C",typeof(String),"A+B");
DataColumn D=_dt.Columns.Add("D",typeof(String),"A+'!'+B");

DataRow _dr=_dt.NewRow();
_dr["A"]="A";
_dr["B"]="B";

Console.WriteLine(_dr["A"]);
Console.WriteLine(_dr["B"]);
Console.WriteLine(_dr["C"]); //Shows blank-why? Expected AB
Console.WriteLine(_dr["D"]); //Shows blank-why? Expected A!B

Add the DataRow to the DataTable, that's when the Expression is first evaluated:

These are calculated columns. When the + symbols is used with Columns of data type String, the values are concatenated.

String Operators

T o concatenate a string, use the + character. The value of the CaseSensitive property of the DataSet class determines whether string comparisons are case-sensitive. However, you can override that value with the CaseSensitive property of the DataTable class.

DataRow _dr=_dt.NewRow();
_dr["A"]="A";
_dr["B"]="B";
_dt.Rows.Add(_dr);

As a note, the four lines above can be written as:

_dt.Rows.Add("A", "B");

The result is of course the same. The values of Columns C and D are not included in the object[] array, but generated by the Columns' Expressions.

Now it should output:

A
B
AB
A!B

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM