从实体框架的组合框中获取ID值

时间:2013-10-24 01:47:40

标签: c# winforms entity-framework combobox

使用ADO.net,如果我想从组合框中检索ID,我就这样做:

int idToGet = int.parse(tbCategory.SelectedValue.ToString());

然后完成,

但是当我用EF绑定组合框时,它会显示错误输入字符串的格式不正确。因此,当前值显示{id = 7,category = TESTING}并且不像往常一样。

这是我的代码段:

    public void loadCategory()
    {
        tbCategory.DataSource = null;

        var listCategoryObj = new malsic_inventoryEntities();

        var query = from cat in listCategoryObj.Category
                    //join cat in listItmObj.Category on n.id_category equals cat.id
                    select new { cat.id,cat.category };

        if (query.Count() > 0)
        {
            tbCategory.DataSource = query.ToList();
            tbCategory.DisplayMember = "category";
            tbCategory.ValueMember = "id";
            tbCategory.Invalidate();
        }
        else
        {
            tbSubCategory.Enabled = false;
        }

    }
    public void loadSubcategory()
    {
        tbSubCategory.DataSource = null;

        int id_category_current = int.Parse(tbCategory.SelectedItem.Value.ToString());

        var listSubCategoryObj = new malsic_inventoryEntities();

        var query = from SubCat in listSubCategoryObj.SubCategories
                    where SubCat.id_category == id_category_current
                    select new { SubCat.id, SubCat.subcategory };

        if (query.Count() > 0)
        {
            groupBox1.Enabled = true;

            tbSubCategory.DataSource = query.ToList();
            tbSubCategory.DisplayMember = "subcategory";
            tbSubCategory.ValueMember = "id";
            tbSubCategory.Invalidate();
        }
        else
        {
            groupBox1.Enabled = false;
        }

    }

我做错了什么?

1 个答案:

答案 0 :(得分:0)

我认为您的问题与ADO.NET或Entity Framework无关。我认为您的问题与int.Parse一致。尝试以这种方式设置id_category_current,而不是现在如何设置:

int id_category_current;
if(!int.TryParse(tbCategory.SelectedItem.Value.ToString(), out id_category_current))
{
   groupBox1.Enabled = false;
   return;
}