List (of T) and Eval - asp.net

I am using a List(of T) in my VB.Net/ASP.Net project. While displaying the list on ASP.net, I am using #Eval, but my date (After formattin) is always displaying the MinVal insteaad of Null Spacs. How to check for date.min on #Eval to get the date as " " when its equal to Date.Min Val

DateTime object can not be Null by default until you define it Nullable. If you want DateTime object to be able to hold null as value then you need to define the object data type as Nullable and explicitly assign Null. By default, any DateTime object is assigned the Min value.
If you want to check if date has Min value, either you can user DateTime.MinValue property or create a new DateTime object (It will be assigned Min value by default) then compare with that object.
[Example]
Public Property MyDate As DateTime?
' get value
<asp:someElement attr='<%# If(Eval("MyDate") Is Nothing, " ", CType(Eval("MyDate"), DateTime?).Value.ToShortDateString()) %>'></asp:someElement>

Related

How to have a value of NULL for DateTime?

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.

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.

ASP.NET Error with session key strings

Hey I am trying to convert the following code to VB.NET from this webpage
http://msdn.microsoft.com/en-us/magazine/cc163730.aspx
And have a method converted as such
' Get the order from the session on demand
Private Shared Function GetOrderFromSession(ByVal i As Integer) As ShoppingCartOrder
Dim session As HttpSessionState = HttpContext.Current.Session
Dim ID As Integer = 0
Dim quantity As Integer = 0
' note: For simplicity session key strings are dynamically
' created——for performance reasons they should be precreated.
ID = CInt(session(ShoppingCartItemIDKeyBase + i))
quantity = CInt(session(ShoppingCartOrderQuantityKeyBase + i))
Dim item As ShoppingCartItem = ShoppingCartItem.GetItem(ID)
Return New ShoppingCartOrder(item, quantity)
End Function
But getting the error around the lines
ID = CInt(session(ShoppingCartItemIDKeyBase + i))
quantity = CInt(session(ShoppingCartOrderQuantityKeyBase + i))
Error 1 Overload resolution failed because no accessible 'Item' can be called without a narrowing conversion:
'Public Default Property Item(index As Integer) As Object': Argument matching parameter 'index' narrows from 'Double' to 'Integer'.
'Public Default Property Item(name As String) As Object': Argument matching parameter 'name' narrows from 'Double' to 'String'.
The + operator can be used for string concatenation as well as the & operator in VB.NET, but the ampersand is the preferred operator.
Just to be sure, can you switch them to ampersands and see if the error still occurs? ShoppingCarItemIDKeyBase is a string, and I'm not sure if the + operator forces the strings to convert to numbers since the user has the option of using &.
ID = CInt(session(ShoppingCartItemIDKeyBase & i))
quantity = CInt(session(ShoppingCartOrderQuantityKeyBase & i))
One or both of these variables is a decimal type rather than an integer:
ShoppingCartItemIDKeyBase
ShoppingCartOrderQuantityKeyBase

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 ;
}

vb.net, option strict, enums and overriding ToString

I have the following code:
Public Enum Country
Canada = 1
USA = 2
End Enum
When I want to see if the user has selected a value, I do:
ddl.SelectedValue = Country.Canada
Which works fine. However, if I turn on a warning for implicit conversion, this gives a warning. Changing it to
ddl.SelectedValue = Country.Canada.ToString()
fails, since the ToString() method returns "Canada" not "1".
What's the best way to get rid of the warning?
You can explicitly cast the SelectedValue to an int, or the Country as a string.
If CInt(ddl.SelectedValue) = Country.Canada
or
If ddl.SelectedValue = CStr(Country.Canada)
If you take the first option, you might need to explicitly declare your enum as Integer
Public Enum Country As Integer
The warning occurs because SelectedValue is a string, and Country is an Integer, so an implicit conversion occurs - just like it says!!
If you want the value '1' rather than 'Canada', you can explicitly cast it as an integer first, and then call .ToString() on the result of that.
ddl.SelectedValue = DirectCast(Country.Canada, Integer).ToString()

Resources