Edit

Share via


DataColumn.Expression Property

Definition

Gets or sets the expression used to filter rows, calculate the values in a column, or create an aggregate column.

public string Expression { get; set; }
[System.Data.DataSysDescription("DataColumnExpressionDescr")]
public string Expression { get; set; }

Property Value

An expression to calculate the value of a column, or create an aggregate column. The return type of an expression is determined by the DataType of the column.

Attributes

Exceptions

The AutoIncrement or Unique property is set to true.

When you are using the CONVERT function, the expression evaluates to a string, but the string does not contain a representation that can be converted to the type parameter.

When you are using the CONVERT function, the requested cast is not possible. See the Conversion function in the following section for detailed information about possible casts.

When you use the SUBSTRING function, the start argument is out of range.

-Or-

When you use the SUBSTRING function, the length argument is out of range.

When you use the LEN function or the TRIM function, the expression does not evaluate to a string. This includes expressions that evaluate to Char.

Examples

The following example creates three columns in a DataTable. The second and third columns contain expressions; the second calculates tax using a variable tax rate, and the third adds the result of the calculation to the value of the first column. The resulting table is displayed in a DataGrid control.

private void CalcColumns()
{
    DataTable table = new DataTable ();

    // Create the first column.
    DataColumn priceColumn = new DataColumn();
    priceColumn.DataType = System.Type.GetType("System.Decimal");
    priceColumn.ColumnName = "price";
    priceColumn.DefaultValue = 50;

    // Create the second, calculated, column.
    DataColumn taxColumn = new DataColumn();
    taxColumn.DataType = System.Type.GetType("System.Decimal");
    taxColumn.ColumnName = "tax";
    taxColumn.Expression = "price * 0.0862";

    // Create third column.
    DataColumn totalColumn = new DataColumn();
    totalColumn.DataType = System.Type.GetType("System.Decimal");
    totalColumn.ColumnName = "total";
    totalColumn.Expression = "price + tax";

    // Add columns to DataTable.
    table.Columns.Add(priceColumn);
    table.Columns.Add(taxColumn);
    table.Columns.Add(totalColumn);

    DataRow row = table.NewRow();
    table.Rows.Add(row);
    DataView view = new DataView(table);
    dataGrid1.DataSource = view;
}

Remarks

For more information about this API, see Supplemental API remarks for DataColumn.Expression.

Applies to

Product Versions
.NET Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 2.0, 2.1

See also