Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Constraint on DataColumn in C# DataTable?

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).

like image 217
Rafael Emshoff Avatar asked Jan 14 '23 00:01

Rafael Emshoff


2 Answers

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;
  }
}
like image 95
LarsTech Avatar answered Jan 19 '23 00:01

LarsTech


I can recommend you to forget about data tables and use classes. You can use data annotation to validate your model.

Use this attribute to validate a range of values for an specific property/

This code is extracted from the specified article(example of class making the validation of a range):

public class Product
{

  [Range(5, 50)]
  public int ReorderLevel { get; set; }

  [Range(typeof(Decimal),"5", "5000")]
  public decimal ListPrice { get; set; }

}

Your are going to find a lot of benefits of using classes.

like image 31
Juan Avatar answered Jan 19 '23 01:01

Juan