问题
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