Now i understand the problem. The second and third columns are double
-columns. Of course you can'd add values like 11/09/2015
. How would you want to convert that to double? You either have to tell us how you want to convert it or use String
as DataColumn
-type.
One option would be to use DateTime.ToOADate()
which is the ole automation date:
DataRow firstRow = table.NewRow();
for (var i = 0; i < table.Columns.Count; i++)
{
string colName = table.Columns[i].ColumnName;
DateTime dt;
double d;
if(DateTime.TryParse(colName, out dt))
firstRow.SetField(i, dt.ToOADate());
else if(double.TryParse(colName, out d))
firstRow.SetField(i, d);
}
table.Rows.InsertAt(firstRow, 0);
Another way would be to check the column-type:
DataRow firstRow = table.NewRow();
for (var i = 0; i < table.Columns.Count; i++)
{
DataColumn col = table.Columns[i];
if (col.DataType == typeof(string))
{
firstRow.SetField(i, col.ColumnName);
}
else if (col.DataType == typeof(DateTime))
{
DateTime dt;
if (DateTime.TryParse(col.ColumnName, out dt))
firstRow.SetField(i, dt);
}
else if (col.DataType == typeof(double))
{
double d;
if (double.TryParse(col.ColumnName, out d))
firstRow.SetField(i, d);
}
}
table.Rows.InsertAt(firstRow, 0);
But this natural approach would not solve your issue since you have a DateTime
value that has to be converted to a double
.
The third and easiest approach would be use use String
as column-type.
DataTable table = new DataTable();
table.Columns.Add("Title");
table.Columns.Add("11/09/2015"); // string is default
table.Columns.Add("23/01/2015");
DataRow firstRow = table.NewRow();
for (var i = 0; i < table.Columns.Count; i++)
{
string colName = table.Columns[i].ColumnName;
firstRow.SetField(i, colName);
}
table.Rows.InsertAt(firstRow, 0);
That works always.