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()
Related
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.
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
In ASP.net is the following code right ?
Dim r1 As Bollean = rd1.checked
checkbox returns what type of value?
then when I put this following code---
If Request.QueryString("r3") Then
myReportDocument.Load(Server.MapPath("Gradewise.rpt"))
End If'
It gives following error--
Conversion from string "" to type 'Boolean' is not valid.
.checked property returns a boolean value.
And regarding error that you are getting - you are trying to put a string in a if statement while a condition which returns either true or false is expected.
So it should be
'If Request.QueryString("r3")="some string to compare" Then ...
as Request.QueryString("r3") returns a String!
You need to use Checked property of checkbox to get the checked status of checkbox. rd1.checkbox would return object of type CheckBox
Dim r1 As Bollean = rd1.checkbox.Checked
Edit as OP is edited. You have to give expression that results in boolean in if statement.
If Request.QueryString("r3") == "somevalue" Then
myReportDocument.Load(Server.MapPath("Gradewise.rpt"))
End If'
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.
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