Setting an item value in a DataRow does not work

I am trying to convert all DateTime values ​​in a DataTable to strings. Here is the method I'm using:

private static void ConvertDateTimesToStrings(DataTable dataTable) { if (dataTable == null) { return; } for (int rowIndex = 0; rowIndex < dataTable.Rows.Count; rowIndex++ ) { for (int i = 0; i < dataTable.Columns.Count; i++) { DateTime dateTime; try { dateTime = (DateTime)dataTable.Rows[rowIndex][i]; } catch (InvalidCastException) { continue; } dataTable.Rows[rowIndex][i] = dateTime.ToString("dd.MM.yyyy hh:mm:ss"); } } } 

After executing this line:

 dataTable.Rows[rowIndex][i] = dateTime.ToString("dd.MM.yyyy hh:mm:ss"); 

I check the value of dataTable.Rows [rowIndex] [i] and see that it is still a DateTime, not a string. Why is this happening and how can I solve it?

Edit: I am trying to do this because I am struggling with api, and unfortunately I have no choice which component to use.

+4
source share
3 answers

Perhaps he determined that the data type of the column is the time of the date and reset the values ​​to datetime when you store the value back there.

Try this ... Create a new column in datatable as TypeOf (String) and store the value of the row in this column. When all values ​​have been copied, release the date time column.

+6
source

It just won't work because you haven't changed the data type of the lining.

You have a DataTable with a column that has a DateTime data type.

You can assign it a String, but it will convert back to DateTime.

Why do you want to change it to a formatted string? Can you format only when you need to display it and treat it as a DateTime until you show it?

Update: it is also better if you check the type of the column before trying to convert it, it can be much faster:

 if (dataTable.Columns[0].DataType == typeof(DateTime)) { } 
+14
source

This will not work, because the DataType of the column is DateTime anyway, and it will convert the string back to datetime. I would suggest formatting the date to a string when generating your API message. If you still need to create a string column for datetime values

 foreach (DataColumn column in dataTable.Columns) { if (column.DataType == typeof(DateTime)) { dataTable.Columns.Add(column.ColumnName + "_string", typeof(string)); } } foreach (DataRow row in dataTable.Rows) { foreach (DataColumn column in dataTable.Columns) { if (column.DataType == typeof(DateTime)) { row[column.ColumnName + "_string"] = row[column.ColumnName].ToString("dd.MM.yyyy hh:mm:ss"); } } } 

You can then delete all DateTime columns or use dataTable.Select () to get only the columns you need. PS: I have not tested the code, it is up to you.

+1
source

Source: https://habr.com/ru/post/1277762/


All Articles