简体   繁体   English

如何正确连接 DataTable 的列的值?

[英]How to properly concatenate the values of Columns of a DataTable?

In the following code, I noticed that Columns A and B show data.在下面的代码中,我注意到A列和B列显示数据。
However, columns C and D are empty.但是,列CD为空。 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:将 DataRow 添加到 DataTable,这是第一次评估Expression的时间:

These are calculated columns.这些是计算列。 When the + symbols is used with Columns of data type String, the values are concatenated.+符号与数据类型 String 的列一起使用时,这些值被连接起来。

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. DataSet class 的 CaseSensitive 属性的值确定字符串比较是否区分大小写。 However, you can override that value with the CaseSensitive property of the DataTable class.但是,您可以使用 DataTable class 的 CaseSensitive 属性覆盖该值。

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.CD的值不包含在object[]数组中,而是由列的表达式生成。

Now it should output:现在应该是 output:

A
B
AB
A!B

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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