简体   繁体   中英

Format Exception when converting string to short C#

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 EG : "when converting a string to datetime parse the string to take the date before putting each variable"

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");             

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.

short关键字表示一种整数数据类型,该类型根据以下博客中显示的大小和范围存储值

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