What I've seen are good recommendations although you (with no disrespect) are blindly making attempts without understanding the mechanics. When stuck like this step outside of the application, create either a unit test project or console project and figure out how to do
what is needed which not only solves the problem but also gives you knowledge.
For example in the following console project I mocked up two different ways to contain a TimeSpan
in a DataTable
which in a real application would had been read from a database table.
- UsingString() stores time as a string, not recommended, always strong type objects/values
- StronglyTyped() stores time as a TimeSpan
To keep code clean and also usable in the real application here are several extension methods to consider and are used in the code below.
public static class Extensions
{
public static bool IsNullOrWhiteSpace(this string sender) => string.IsNullOrWhiteSpace(sender);
public static TimeSpan ToTimeSpan(this string sender) => TimeSpan.Parse(sender);
public static bool IsValidTimeFormat(this string sender) => TimeSpan.TryParse(sender, out _);
public static T GetValue<T>(this IDataReader sender, string columnName)
{
var value = sender[columnName];
return value == DBNull.Value ? default : (T)value;
}
}
Code samples to learn from
using System;
using System.Data;
namespace TimeSpanDataTable
{
class Program
{
static void Main(string[] args)
{
Console.Title = "Code sample";
UsingString();
StronglyTyped();
Console.ReadLine();
}
private static void UsingString()
{
Console.ForegroundColor = ConsoleColor.Cyan;
Console.WriteLine($"{nameof(UsingString)}: Using string");
Console.ResetColor();
DataTable dataTable = new DataTable();
dataTable.Columns.Add(new DataColumn("StartTime", typeof(string)));
dataTable.Rows.Add("10:10:0");
dataTable.Rows.Add("");
dataTable.Rows.Add("10:10:0");
dataTable.Rows.Add("10-10/0");
foreach (DataRow row in dataTable.Rows)
{
if (row.Field<string>("StartTime").IsNullOrWhiteSpace())
{
Console.WriteLine("Empty");
}
else
{
if (row.Field<string>("StartTime").IsValidTimeFormat())
{
Console.WriteLine(row.Field<string>("StartTime").ToTimeSpan());
}
else
{
Console.WriteLine($"{row.Field<string>("StartTime")} not valid");
}
}
}
Console.WriteLine();
}
private static void StronglyTyped()
{
Console.ForegroundColor = ConsoleColor.Cyan;
Console.WriteLine($"{nameof(StronglyTyped)}: Using TimeSpan");
Console.ResetColor();
DataTable dataTable = new DataTable();
dataTable.Columns.Add(new DataColumn("StartTime", typeof(TimeSpan)));
dataTable.Rows.Add(DateTime.Now.TimeOfDay);
dataTable.Rows.Add();
dataTable.Rows.Add(new TimeSpan(10, 0, 0));
foreach (DataRow row in dataTable.Rows)
{
var test = row["StartTime"];
if (row["StartTime"] != DBNull.Value)
{
Console.WriteLine(row.Field<TimeSpan>("StartTime"));
}
else
{
Console.WriteLine("Null");
}
}
}
}
}