未处理的类型' System.InvalidCastException'发生了...无法转换类型为' System.String'的对象输入

时间:2017-05-17 11:56:59

标签: c# linq

可以有人帮我吗?遵循我的代码和"未处理的类型' System.InvalidCastException'发生在GelatoProject.exe

附加信息:无法转换类型为' System.String'的对象键入' GelatoProject.RecipeVariables'。"是消息。

// ...
using (var db = new GelatoProjectDBEntities())
{
    RecipeVariables selected = 
        (RecipeVariables)comboBoxRecipeDetail.SelectedItem;

    var results = (from x in db.Recipe_Parameters
                select new RecipeVariables 
                        { 
                            Id = x.Id, 
                            RecipeDetail = x.recipeDetail, 
                            Parameter = x.parameter, 
                            RangeDetail = x.rangeDetail, 
                            RangeValue = x.value.ToString() 
                        }
               )
                .Where(x => x.RecipeDetail == selected.RecipeDetail && x.Parameter == "totalsolids" && x.RangeDetail == "Max")
                .FirstOrDefault();

    totsolidsRangeMax = decimal.Parse(results.RangeValue);

    MessageBox.Show(totsolidsRangeMax.ToString());
}
// ...

class RecipeVariables
{
    public int Id { get; set; }
    public string NameIngredient { get; set; }
    public string Brand { get; set; }
    public string LBName { get { return NameIngredient + " - " + Brand;}}
    public string RecipeDetail { get; set; }
    public string Parameter { get; set; }
    public string RangeDetail { get; set; }
    public string RangeValue { get; set; }
}

1 个答案:

答案 0 :(得分:2)

RecipeVariables selected = (RecipeVariables)comboBoxRecipeDetail.SelectedItem;

comboBoxRecipeDetail.SelectedItem是一个字符串 - 您在单击组合框时看到的文本。它无法转换为RecipeVariables

将您的代码更改为:

using (var db = new GelatoProjectDBEntities())
{
    RecipeVariables selected = new RecipeVariables()
                               {
                                   RecipeDetail = (string)comboBoxRecipeDetail.SelectedItem
                               };

    // var results = ...
}

这将创建一个新的RecipeVariables对象,然后将其RecipeDetail属性设置为所选组合框项目的文本。