繁体   English   中英

发生类型为'System.InvalidCastException'的未处理异常…无法将类型为'System.String'的对象转换为类型

[英]unhandled exception of type 'System.InvalidCastException' occurred…Unable to cast object of type 'System.String' to type

有人可以帮我吗? 遵循我的代码和“ GelatoProject.exe中发生了'System.InvalidCastException类型的未处理的异常”

附加信息:无法将类型为“ 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; }
}
RecipeVariables selected = (RecipeVariables)comboBoxRecipeDetail.SelectedItem;

comboBoxRecipeDetail.SelectedItem是一个字符串-单击组合框时看到的文本。 不能RecipeVariablesRecipeVariables

将您的代码更改为:

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

    // var results = ...
}

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM