代码之家  ›  专栏  ›  技术社区  ›  loki

错误:Linq中的用户代码未处理FormatException如何解决?

  •  0
  • loki  · 技术社区  · 16 年前

    alt text

    请看下面这个代码抛出我:FormatException是未经处理的用户代码

    代码:

     satis.KDV = Decimal.Parse((from o in genSatisctx.Urun where o.ID == UrunID select o.Kdv).ToString());

    如何重写linq查询?

    3 回复  |  直到 7 年前
        1
  •  2
  •   Jeff Yates    16 年前

    你在打电话吗 ToString 而不是单个结果。即使您可能只期望一个值与查询匹配,它也不会只返回一个值。你必须指示它使用 Single First Last 或者也返回默认值的变量( SingleOrDefault FirstOrDefault , LastOrDefault ).

    为了避免异常,可以将其更改为 Decimal.TryParse 或者,如果LINQ查询返回无法正确解析的内容,可以将代码更改为使用默认值。我推荐前者或两者兼而有之。

    SingleOrDefault . 这可以确保只解析一个值,即使找不到值,并且如果有多个结果,我们会得到一个异常(即,它强制我们在查询中只得到零个或一个结果)。

    decimal parsedValue;
    if (Decimal.TryParse(
         genSatisctx
         .Urun
         .Where(o => o.ID == UrunID)
         .Select(o=>o.Kdv)
         .SingleOrDefault()
         .ToString(), out parsedValue))
    {
       satis.KDV = parsedValue;
    }
    
        2
  •  1
  •   Jon Skeet    16 年前

    ToString() IQueryable<T>

    我猜你想打电话给我 First() Single() ,但如果没有更多的信息,我们真的说不出来。这是什么类型的 o.Kdv ?

    我猜你要么想要:

    satis.KDV = (from o in genSatisctx.Urun 
                 where o.ID == UrunID 
                 select o.Kdv).First();
    

    string kdvString = (from o in genSatisctx.Urun 
                        where o.ID == UrunID 
                        select o.Kdv).First();
    decimal kdv;
    if (decimal.TryParse(kdvString, out kdv))
    {
        satis.KDV = kdv;
    }
    else
    {
        // What do you want to do if it's not valid?
    }
    
        3
  •  0
  •   Brian Webster Jason    13 年前

     /*   protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
               try
              {
    
                TextBox name = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txtEditName");
                SqlDataSource2.UpdateParameters["Name"].DefaultValue = name.ToString();
    
                TextBox age = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txtEditAge");
                SqlDataSource2.UpdateParameters["Age"].DefaultValue = age.ToString();
    
                TextBox birthday = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txtEditBirthday");
                SqlDataSource2.UpdateParameters["Birthday"].DefaultValue = birthday.ToString();
    
                DropDownList country = (DropDownList)GridView1.Rows[e.RowIndex].FindControl("DropEditCountry");
                SqlDataSource2.UpdateParameters["CountryID"].DefaultValue = country.SelectedValue;
    
    
                TextBox mobile = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txtEditMobile");
                SqlDataSource2.UpdateParameters["Mobile_No"].DefaultValue = mobile.ToString();
                SqlDataSource2.Update();
            }
            catch (Exception j)
           {
           j.Message.ToString();
           }
        }
    
    /* }