Вопрос

I'm trying to convert a string to a short in C#. But i keep getting a format exception was unhandled error.

short copies = short.Parse(mainForm.quantityBox.Text);
printDocument.PrinterSettings.Copies = copies;

The value in the quantityBox is "1".

The tip that Visual Studio gave me is not really helpfull E.G : "when converting a string to datetime parse the string to take the date before putting each variable"

Это было полезно?

Решение

Try adding a ToString call:

short copies = short.Parse(mainForm.quantityBox.Text.ToString());

The reason you were getting the exception is because quantityBox had a value of 1 which is an int. short.Parse() takes a string, so by casting the contents of quantityBox.Text to ToString(), no matter what value it is given, it will be converted to a string.

Другие советы

Format exception will occur if your input text value id having "." (dot) in it. Better to replace or handle this dot(.) to avoid "Input string was not in a correct format.".

This will throw error:

short val = short.Parse("4.0");                  

This will not throw any error:

short val1 = short.Parse("4");             

The short keyword denotes an integral data type that stores values according to the size and range shown in the following Blog

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top