0

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?

5
  • As the error says, the RHS is returning a string whereas you are expecting byte. Could you please paste a sample value from that combo box and also let us know what should go in startUp? Commented Mar 30, 2017 at 4:38
  • you are trying to assign a string to startUp which is of Byte datatype... Commented Mar 30, 2017 at 4:39
  • Cause cmbStart.SelectedIndex.ToString(); equal to index value in string. if index is 0 it will return 0 as value in string. Commented Mar 30, 2017 at 4:39
  • You need to list the actual error, either selectedIndex is null (in which cas use something like String.Format("{0}", cmbStart.SelectedIndex) or cmbStart is itself not yet initialised (so null). .ToString() works for all system types that are not null. (it is possible for user defined types to throw an exception but that is a discussion for another day) Commented Mar 30, 2017 at 4:43
  • 1
    Try running VB.NET with Option Strict On and this conversion will also fail. VB lets you do some dopey things by default. Commented Mar 30, 2017 at 5:44

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

1 Comment

@RubelHosen i updated my answer with some useful links about this issue, take a look
0

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

1 Comment

This returns a char. Even if you convert that to byte it won't be the real index but the character code of the first digit of the index. For example if item 12 is selected in the combo box, it will return the ASCII code for '1'.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.