簡體   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