未处理的异常输入字符串格式不正确

本文关键字:格式 不正确 字符串 输入 异常 未处理 | 更新日期: 2023-09-27 18:33:14

我想在我的程序中添加异常处理,以显示在向用户的消息框中。"输入的格式不正确,请输入一个数值"作为我的产品价格值。目前,当我输入错误的格式(例如字符串值)时,我会收到一条错误消息,指出未处理的异常输入字符串格式不正确。取而代之的是,我希望出现一个消息框。谁能指出我正确的方向。谢谢。我在程序中使用的代码如下。

 if (result == System.Windows.Forms.DialogResult.Yes)
                    {
                        // update the employee record
                        ((Employee)o).ProductName = this.textProdName.Text;


                        ((Employee)o).ProductPrice = Convert.ToDouble(this.textProdPrice.Text); 

                        ((Employee)o).ProductId = this.textProdID.Text;
                        ((Employee)o).ProductQuantity = Convert.ToInt32(this.textProdQuantity.Text);

                        MessageBox.Show(((Employee)o).ProdName + " record has been updated with new                       details, except the ID.");

未处理的异常输入字符串格式不正确

使用 TryParse 而不是执行盲转换,假设该值可能有效。然后,您无需担心引发异常,如果操作返回false,则只需显示警报即可。

下面是来自 MSDN 的示例

double number;
value = Double.MinValue.ToString();
if (Double.TryParse(value, out number))
   Console.WriteLine(number);

如果操作成功TryParse则返回 true,并且 number 的值将使用提取的双精度值进行更新。