简体   繁体   中英

Cannot implicitly convert type 'string' to 'byte' in c#

For example consider the following code:

Properties.Settings.Default.startUp = cmbStart.SelectedIndex.ToString();

in vb.net the same approach works fine but in c# it's not. Here startUp is user defined setting which is type byte and cmbStart is a ComboBox . What can I do to fix this error?

The difference is that VB.Net allow string to be implicitly converted into byte, and throw an exception if the value cannot be converted, but c# doesn't allow string to be implicitly converted.

SelectedIndex is of type integer, try casting it to byte instead of using ToString() method,use the following code:

Properties.Settings.Default.startUp = (byte)cmbStart.SelectedIndex;

Useful Links

You cann't. String type contain multiple byte you can choose maybe one of it's character

cmbStart.SelectedIndex.ToString()[0]

this will return first character of the converted index to string (probably not what you want). but if you combo box doesn't has more than 256 item to select from, you can convert the returned value for selected item to byte and store it in startup.

(byte)cmbStart.SelectedIndex

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM