Reputation: 83
There is a class called DisplayTable
. Later binding to some observation Collection and then populating the values to the datatable
.
I need the value column of the table should accept only integers, decimals, double.
public class DisplayTable
{
public string AnalyteName { get; set; }
public string Units { get; set; }
[RegularExpression(@"0-9+(.)", ErrorMessage="This field accept Only numeric values")]
public float ReferenceValue { get; set; }
}
//Binding the class to Collection
public ObservableCollection<DisplayTable> list { get; set; }
// creating an istance to the class
DisplayTable d = new DisplayTable();
d.AnalyteName ="c"
d.Units= "mg"
this.list.Add(d)
table.Columns.Add("Analyte Name");
table.Columns.Add("Units");
table.Columns.Add("Value");
foreach (var item in this.list)
{
drn = table.NewRow();
int col = 0;
drn[col] = item.AnalyteName ;
drn[col + 1] = item.Units;
drn[col + 2] = item.ReferenceValue;
table.Rows.Add(drn);
table.AcceptChanges();
}
dataGrid.ItemsSource = table.DefaultView;
Upvotes: 1
Views: 963
Reputation: 82474
A DataColumn
have a data type, exposed through it's DataType
property.
The Add
method of the DataColumnCollection
have several overloads, some of which allows you to specify the data type of the column.
The overload you are currently using uses the default data type, which is a string.
If you want to specify a different data type, use another overload:
table.Columns.Add("Value", typeof(decimal));
However, you are interested in a column that can hold multiple data types - integers, decimals doubles and floats - and those data types are not interchangeable.
I've chosen decimal
data type since it is more accurate then a double
, however since there is no implicit conversion between the other floating points data types (float
, double
) and decimal
you will have to explicitly cast the value to decimal
when setting the cell value:
foreach (var item in this.list)
{
drn = table.NewRow();
int col = 0;
drn[col] = item.AnalyteName ;
drn[col + 1] = item.Units;
drn[col + 2] = (decimal) item.ReferenceValue;
table.Rows.Add(drn);
table.AcceptChanges();
}
Upvotes: 1