0

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.

  • 2
    You didn't mention what Items you added to that ComboBox or what its DataSource is. Did you add strings or the values of the enumerator (`[Enum].GetNames()`, `[Enum].GetValues()` or similar) – Jimi Oct 18 '20 at 17:09
  • 1
    Also, is you question about VB or C#? The `{ }` are C#, the missing `;` points to `VB`. **CS____** exceptions are C#. – Olivier Jacot-Descombes Oct 18 '20 at 17:18

1 Answers1

0

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:

Olivier Jacot-Descombes
  • 104,806
  • 13
  • 138
  • 188
  • Thank you for the help! It spits out cs0103 and cs0119 after i change the code –  Oct 18 '20 at 17:01
  • I have taken the type name `FastColoredTextBoxNS.Language` from the error message. Maybe you have import a namespace to make it work. Btw. These are C# error messages but you specified vb.net as tag. So the right answer for C# would be `fastColoredTextBox1.Language = (TheTypeNameHere)comboBox1.SelectedItem;`. The functions/operators `CType` and `DirectCast` are VB. – Olivier Jacot-Descombes Oct 18 '20 at 17:10