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).
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;
}
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With