How to have a value of NULL for DateTime? - asp.net

In my SQL database, I've declared DpsDate and AdmDate as DATE, also I've set them to allow nulls. When I run my application and leave these columns blank, I get this error:
Failed to convert parameter value from a String to a DateTime.
This is where I'm a bit confused because I've set them to allow nulls so shouldn't the database accept no value? The application works if I set both dates to "01/01/1900". I've tried setting them to "00/00/0000" but I get the same error.
Here's what I have:
If tbNotifyDate.Text = "" Then
cmd.Parameters.Add("#DpsDate", SqlDbType.Date, 50).Value = "01/01/1900"
Else
cmd.Parameters.Add("#DpsDate", SqlDbType.Date, 50).Value = tbNotifyDate.Text
End If
If tbAdmDate.Text = "" Then
cmd.Parameters.Add("#AdmDate", SqlDbType.Date, 50).Value = "01/01/1900"
Else
cmd.Parameters.Add("#AdmDate", SqlDbType.Date, 50).Value = tbAdmDate.Text
End If

You need to use DBNull.Value to represent NULL in ADO.NET. Things like table adapters and Entity Framework, which are built on top of ADO.NET, can support nullable value types and thus use Nothing to represent NULL but ADO.NET itself predates nullable value types, so Microsoft had to invent a type specifically for the purpose of representing NULL.
I would suggest using the If operator to make the code more concise:
Dim value As Date
cmd.Parameters.Add("#AdmDate", SqlDbType.Date).Value = If(Date.TryParse(tbAdmDate.Text, value),
value,
CObj(DBNull.Value))
The CObj is required because the two possible results of If must be the same type and Date and DBNull are not the same type. By casting one possible result as type Object, they are both interpreted as type Object and the compiler is happy.
Note that, as I have written that example, this will save NULL if the TextBox contains anything that isn't a valid representation of a Date. You can use whatever validation is appropriate in your specific case or, if you've already validated, just check for an empty TextBox and use CDate.

Related

How to cast an object in sqlite as only Date and pass date from a parameterised query

So I'm trying to check if some of my values match, for that I'm using an SQLite object and casting it as date and passing it as a parameter which is also a Date, I just want to know if this is the right way to do it?
"AND R1.TIMING = ?
AND R1.VARIETY = ?
AND R1.JOBACRES = ?
AND CAST (R1.PLANTINGDATE AS DATE) = ?
new object[] { item.TIMING, item.VARIETY, item.JOBACRES, item.PLANTINGDATE.Date }).ToList();
This is written in C#, since I want to execute this query in C# with SQLite, any inputs would be helpful

Option Strict disallows late binding using IEnumerable

Dim distinctJoints As IEnumerable
distinctJoints = From row In spotsTable.AsEnumerable()
Group row By Key = row("FUNCJOINTCODE") Into Group
Select Key, Group
_evaluatedJointsCount = (From row In spotsTable.AsEnumerable()
Group row By Key = row("FUNCJOINTCODE") Into Group
Select Key, Group).Count()
'Process each joint
For Each currentJoint In distinctJoints
Dim currentJointKey As String = currentJoint.Key
For the above code currentJoint.Key is showing error of late binding after option strict is on.
Could you please help me out of this.
First, let me congratulate your for moving your code towards Option Strict On! It might be some work in the beginning, but it pays off in the long run since a lot of errors will be found at compile-time rather than at run-time.
That said, let's look at your problem. Here:
Dim distinctJoints As IEnumerable
you declare distinctJoints as a non-generic IEnumerable. A non-generic IEnumerable returns items of type Object when iterated over. The type Object does not contain a Key method. This is why you get a compile-time error.
Since your LINQ query returns a generic IEnumerable of an anonymous type, the solution is to use type inference instead. Activate Option Infer On (if you have not already done so) in your project properties and let the compiler infer the correct data type:
' Dim distinctJoints As IEnumerable <-- remove this
Dim distinctJoints = From row In spotsTable.AsEnumerable()
Group row By Key = row("FUNCJOINTCODE") Into Group
Select Key, Group

Failed to convert parameter value from a TimeSpan to a DateTime

I am trying to store a time from my textbox field value but I got this exception error, what am I doing wrong? Thanks!:
Failed to convert parameter value from a TimeSpan to a DateTime.
Passing textbox value:
.CamActiveDateFrom = CDate(uitxtCamDateStart.Text.Trim)
My variable and property:
Private _camActiveTimeFrom As Nullable(Of TimeSpan)
Public Property CamActiveTimeFrom() As Nullable(Of TimeSpan)
Get
Return Me._camActiveTimeFrom
End Get
Set(ByVal value As Nullable(Of TimeSpan))
Me._camActiveTimeFrom = value
End Set
End Property
Parameter:
AddInParameter(dbCommand,
"#ActiveTimeFrom", DbType.Time, 6, DBNull.Value)
If (.CamActiveTimeFrom).HasValue Then
dbCommand.Parameters("#ActiveTimeFrom").Value = .CamActiveTimeFrom
End If
DbType.Time is documented as:
A type representing a SQL Server DateTime value. If you want to use a SQL Server time value, use SqlDbType.Time.
So either use SqlDbType.Time instead, or set the value to a DateTime value instead of a TimeSpan value.
Admittedly this mapping table show the DbType.Time mapping to TimeSpan, so there's some inconsistency here - but if you can use a more specific type, that can only be good.
Of course it's easy to construct a DateTime from a TimeSpan if you want to - you should probably decide on a specific date to always use (e.g. 1st January 2000) so that you can then compare values within the database and effectively get a comparison of just the time bits.
I hav the same problem. And I soloved it just used "ToString()".
my code as following:
the date type of "info.START_TIME" is TimeSpan.
db.AddInParameter(dbCommand, "#START_TIME", DbType.Time, info.START_TIME.ToString());
In order to use AddInParameter with a column of data type time, you need to use the SqlDbType instead of DbType (as described in Jon Skeet's answer)
db.AddInParameter(dbCommand, "#ActiveTimeFrom", SqlDbType.Time, 6, DBNull.Value)
instead of
db.AddInParameter(dbCommand, "#ActiveTimeFrom", DbType.Time, 6, DBNull.Value)
BUT.
In order you use SqlDbType.Time instead of DbType.Time, you must declare your Database object as an SqlDatabase, that is
SqlDatabase db = (SqlDatabase)DatabaseFactory.CreateDatabase();
instead of
Database db = DatabaseFactory.CreateDatabase();
as otherwise it won't take the parameter.

check for null with HtmlAgilityPack

How do you check for null with HtmlAgilityPack? I'm getting "Property or indexer 'HtmlAgilityPack.HtmlNode.HasChildNodes' cannot be assigned to -- it is read only" with the following.
if (Node.Element("TD").HasChildNodes = DBNull.Value)
I"m getting "Object reference not set to an instance of an object. " with
if (Node.Element("TD").HasChildNodes)
First, the = operator is the assignment operator, not the comparison operator (==). In your first example you are trying to assign DBNull.Value to HasChildeNodes, a read-only property, not compare it to a value.
Second, you don't test against DBNull.Value, but against null. DBNull.Value is to be used when testing values of items returned by the database using ADO.NET. For all other cases, you should use null.
So, the test should be:
if (Node.Element("TD").HasChildNodes == null)

Pass a NULL in a parameter to a DateTime field in a stored procedure

I have a stored procedure which updates a database using the parameters I supply but I'm having trouble passing a NULL to the stored procedure
The field I need to make NULL is a DateTime field
DB.Parameters.AddWithValue("#date", NULL)
This gives me the error
'NULL' is not declared. 'Null' constant is no longer supported; use 'System.DBNull' instead
So I tried
DB.Parameters.AddWithValue("#date", DBNull.Value.ToString())
But this produces the value 1900-01-01 00:00:00.000 in the column as it's passing a "" to the field
I also tried
DB.Parameters.AddWithValue("#date", DBNull.Value)
But it produces this error
Value of type 'System.DBNull' cannot be converted to 'String'.
Has anybody got any ideas?
Or you can add your parameter like this, which gives it a null value in the database if your variable is null:
DB.Parameters.AddWithValue("#date", myDateTime ?? (object)DBNull.Value);
you need to set it as a nullable type as Amit mentioned.
More details and background available at http://evonet.com.au/overview-of-c-nullable-types/
Try something like this, using Add rather than AddWithValue:
DB.Parameters.Add("#date", SqlDbType.DateTime).Value = DBNull.Value;
Try this
If you are using class and its property and those property values are used as parameter then you can do this
chnage the signature of the property to
public DateTime? myDateTime = null;// Here ? is used to make the property nullable.
Also if your date column is of type varchar then correct it to Date (Sql2008) / DateTime(2005).
//change parameter to this
#SomeDate datetime = null (as suggested by chris)
Allow the field to accept null and then pass the value as
DB.Parameters.Add("#date", DBNull.Value)
This is an example. It's work for me
if(obj.myDate == DateTime.MinValue)
{
aCommand.Parameters.Add("dateParameter", SqlDbType.Date).Value = DBNull.Value;
}
else
{
aCommand.Parameters.Add("dateParameter", SqlDbType.Date).Value = obj.myDate ;
}

Resources