I'm working on a program, and I need to be able to change a setting using a combobox. I'm getting
CS0266 Cannot implicitly convert type 'object' to 'FastColoredTextBoxNS.Language'. An explict conversion exists (are you missing a cast?)
Using the code:
{
fastColoredTextBox1.Language = comboBox1.SelectedItem
}
Does anyone know a simple way to fix this? If any more info is needed, I will gladly edit it in.
You must cast to the desired type, since the SelectedItem property returns the unspecific type Object.
fastColoredTextBox1.Language = DirectCast(comboBox1.SelectedItem, FastColoredTextBoxNS.Language)
Note there is also the CType function. In addition to performing type casts it also performs also type conversions. We do not need a conversion here, if the items in the ComboBox are of the required type. DirectCast just means, okay I know that the item with the runtime type Object is of the required type, just take it as such.
See also:
Casting DataTypes with DirectCast, CType, TryCast
Difference between DirectCast() and CType() in VB.NET
Related
I'm using Authorize.net API and they require card expiration field to be formated as "yyyy-mm". We did that with this simple line of code:
expirationDate = model.Year.ToString("D4") & "-" & model.Month.ToString("D2")
and this absolutelly worked. I still have cards stored in the system that were saved using this method! But today I was testing something completelly unrelated, and wanted to add another card, and bam, this code exploded with this exception:
System.InvalidCastException: 'Conversion from string "D4" to type 'Integer' is not valid.'
Inner exception to that one is:
Input string was not in a correct format.
This just... doesn't make sense to me. Why in the world is it trying to convert format specifier (D4) into an integer? What input string? What in the world changed in two days?
The problem is that your are using a Nullable(Of Integer). This is a different structure that does not support the overloads of the ToString method a normal Integer has.
You can view the overloads of the Nullable structure here.
I suggest you use the GetValueOrDefault() method to get the proper Integer and also apply the value you expect in case the value is Nothing.
If it is impossible that a instance with a Nothing set for the year reaches this method you can simply use the Value property.
I still do not fully understand why you get this strange error message. Maybe you could check out what the actual method that is called is? Pointing at the method should give you that information. It can't be Nullable(Of Integer).ToString
Well, I found a workable solution and something of an answer thanks to #Nitram's comment. The type of Year/Month property has been changed from Integer to Integer?. Obviously, this isn't a very satisfying answer because I still don't understand why the nullable int can't be formatted, and yet the code compiles perfectly. The working solution for me has been using static format method on String as so:
expirationDate = String.Format("{0:D4}-{1:D2}", model.Year, model.Month)
This works fine even with nullable types.
Compare weirdness when working with LINQ and Entity Framework.
I want to retrieve an ID from my DB and I get this weird message.
I could simply fix it as you can see but I want to understand why this happens.
Question:
Why do I get this error message even if I check with "HasValue" or I use "FirstOrDefault"? It can't be null in my opinion but I obviously miss something.
Add .Value if you are 100% sure the Integer? has a value.
Why do I get this error message even if I check with "HasValue"
Entity Framework just uses the objects you give it. It can't create a new object where OPX_ isn't nullable.
the setOpxRights function presumably takes an Integer as a parameter and Option Strict On won't allow an Integer? to be implicitly converted to an Integer. If you are sure that it will always have a value, pass in cctUser.OPX_Rechte.Value
The compiler is not perfect, we can see that OPX_Rechte will have a value because of the where statment, but for the compiler you are just using a the object cctUser that have an Integer? and it needs an Integer.
I have a Linq query that yields anonymous types. However, now I want to work with the parameters of this anonymous type and it does not seem to work.
For Each obj As Object in Query
Dim row As DataRow = obj.parameter
...
Next obj
Now the compiler throws an error on the expression obj.parameter: "Option Strict On disallows late binding". If I understand it right, the compiler doesnt know the parameters of the anonymous type. I tried Option Infer On (and removed As Object), based on Google results, but it didnt help. Which seems to make sense, because it always seems to be a widening conversion to me.
Is there anyway to fix this, or should I just create a custom type?
The code that declares the anonymous type (i.e. the Select part of your LINQ query) must be in the same method as the the code that uses it and the Query variable's declaration must have an inferred type. You cannot access the properties of an anonymous type after it has been cast to an Object since there is no named type to which you can cast it.
So make sure that your LINQ query (or, at least, the part that Selects into a new anonymous type) is in the same method. E.g.
Dim Query = From prod In products
Select prod.Name, prod.Price
For Each obj in Query
Dim name = obj.Name
...
Next obj
I'm developing a vb.net program with VS2008. In my case, dt_list is a instance member as List(of Single). When I wrote
dt_list = CType(ser2.Deserialize(r), dt_list.GetType())
VS2008 complains about "Type 'dt_list.GetType()' is not defined.".
Why? Thanks in advance.
The reason this is not allowed is that the exact value of the type for GetType() must be determined at runtime. The second parameter of CType can only be an "expression that is legal within an As clause in a Dim statement, that is, the name of any data type, object, structure, class, or interface", for instance, List(Of String), which can be determined at compile time.
The following is accordingly legal:
dt_list = CType(ser2.Deserialize(r), List(Of Single))
EDIT:
Casting to an arbitrary type, where the type is not known at compile time, is more involved, however. The proposed answer to this question in the MSDN Forums shows one approach. Though it's in C#, I will guess the same approach can be used in VB.NET as well.
What are you trying to achieve by selecting the cast type at runtime?
You may be able to solve your problem with an interface.
Dim dt_list As IList = Ctype(ser2.Deserialize(r), IList)
This gives you access to all of the List members in IList.
I want to check multiple controls state in one method, in C# this would be accomplished like so:
if (((CheckBox)sender).Checked == true)
{
// Do something...
}
else
{
// Do something else...
}
So how can I accomplish this in VB?
C#:
(CheckBox)sender
VB:
CType(sender, CheckBox)
VB actually has 2 notions of casting.
CLR style casting
Lexical Casting
CLR style casting is what a C# user is more familiar with. This uses the CLR type system and conversions in order to perform the cast. VB has DirectCast and TryCast equivalent to the C# cast and as operator respectively.
Lexical casts in VB do extra work in addition to the CLR type system. They actually represent a superset of potential casts. Lexical casts are easily spotted by looking for the C prefix on the cast operator: CType, CInt, CString, etc ... These cast, if not directly known by the compiler, will go through the VB run time. The run time will do interpretation on top of the type system to allow casts like the following to work
Dim v1 = CType("1", Integer)
Dim v2 = CBool("1")
Adam Robinson is correct, also DirectCast is available to you.
DirectCast will perform the conversion at compile time but can only be used to cast reference types.
Ctype will perform the conversion at run time (slower than converting at compile time) but is obviously useful for convertng value types.
In your case "sender" is a reference type so DirectCast would be the way to go.
Casting in VB.net uses the keyword ctype.
So the C# statement (CheckBox)sender is equivalent to ctype(sender,CheckBox) in VB.net.
Therefore your code in VB.net is:
if ctype(sender,CheckBox).Checked =True Then
' Do something...
else
' Do something else...
End If