I would recommend using DateTime.TryParse to ensure there is a proper DateTime.
Get user input, assert text is a DateTime and if so pass to a method, in this case in the second code block the data operation is inserting a new record but the same applies for updates too.
if (DateTime.TryParse(TextBox1.Text.Trim(), out var dateTime))
{
var (success, exception, id) = DataOperations.AddNewRecord(dateTime);
if (success)
{
// we can use id var
}
else
{
// failure - log error using exception var about
}
}
else
{
// not a valid date time, tell the user
}
Backend code
public class DataOperations
{
private static string _connectionString =
"Data Source=.\\sqlexpress;Initial Catalog=Examples;Integrated Security=True";
public static (bool success, Exception exception, int id) AddNewRecord(DateTime dateTime)
{
using var cn = new SqlConnection { ConnectionString = _connectionString };
using var cmd = new SqlCommand { Connection = cn };
cmd.CommandText = "INSERT INTO dbo.Table1 (SomeDateTime) " +
"VALUES (@SomeDateTime);" +
"SELECT CAST(scope_identity() AS int);";
cmd.Parameters.Add("@SomeDateTime", SqlDbType.DateTime).Value = dateTime;
try
{
cn.Open();
return (true, null, Convert.ToInt32(cmd.ExecuteScalar()));
}
catch (Exception ex)
{
return (false, ex, -1);
}
}
}