Constraint on DataColumn in C# DataTable?

.net, c#, constraints, datatable, system.data

Solution

One way to do this is to inspect the `e.ProposedValue` in the ColumnChanging event of the DataTable.

To have the constraint on a particular column, you can use the ExtendedProperties collection of the DataColumn to act as your flag to check those constraints:

DataTable dt = new DataTable();
DataColumn dc = new DataColumn("Range", typeof(int));
dc.ExtendedProperties.Add("Min", 0);
dc.ExtendedProperties.Add("Max", 10);
dt.Columns.Add(dc);
dt.ColumnChanging += dt_ColumnChanging;

In the ColumnChanging event, you would check if those properties exist, then use them:

void dt_ColumnChanging(object sender, DataColumnChangeEventArgs e) {
  if (e.Column.ExtendedProperties.ContainsKey("Min") &&
      e.Column.ExtendedProperties.ContainsKey("Max")) {
    int min = (int)e.Column.ExtendedProperties["Min"];
    int max = (int)e.Column.ExtendedProperties["Max"];
    if ((int)e.ProposedValue < min) e.ProposedValue = min;
    if ((int)e.ProposedValue > max) e.ProposedValue = max;
  }
}

Problem

is it possible to create a value range constraint on a DataTable in C#? I'm dynamically adding a column to a DataTable: ``` this.PrimaryCorrelationMatrix.Columns.Add(sName, typeof(int)); ``` but I'd like all values within this Column to be integers from [0, 10]. Can I implement such a constraint directly on the DataTable? The next best option I can think of is to create some object with possible values [0, 10], and instead of typeof(int), using typeof(specialObj).

Original source

Related problems