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

萝らか妹 提交于 2021-01-28 13:42:15

问题


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

回答1:


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

To 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


来源:https://stackoverflow.com/questions/61787253/how-to-properly-concatenate-the-values-of-columns-of-a-datatable

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!