我想将combobbox的内容添加到我的数据库中,但它不起作用。我的组合框的内容来自与“产品”表相关联的“类别”表。我尝试了很多转换错误的事情:
这是我的代码:
Product p = new Product();
p.ProductName = txtNom.Text.Trim();
p.ProductDescription = txtDesc.Text.Trim();
p.ProductQuantityUsed = Convert.ToInt32(numQteUsed.Value);
p.ProductQuantityNew = Convert.ToInt32(numQteNew.Value);
p.CategoryID = cboCat.SelectedText.ToString();
db.Products.Add(p);
db.SaveChanges();
//Combobox
public void FillCbCategories()
{
SamsonEntities db = new SamsonEntities();
cboCat.Items.Clear();
var listCat = (from cats in db.Categories
select new CategoryDisplay()
{
CategoryID = cats.CategoryID,
CategoryName = cats.CategoryName
}).ToList();
for(var i=0;i<listCat.Count;i++)
{
cboCat.Items.Add(listCat[i]);
}
}
答案 0 :(得分:1)
根据您的评论判断,您的组合框没有正确绑定到您发送给它的数据。
您可以尝试设置ValueMember和DisplayMember:
cboCat.ValueMember = "CategoryID";
cboCat.DisplayMember = "CategoryName";
在您的方法中,如下所示:
public void FillCbCategories()
{
SamsonEntities db = new SamsonEntities();
cboCat.Items.Clear();
var listCat = (from cats in db.Categories
select new CategoryDisplay()
{
CategoryID = cats.CategoryID,
CategoryName = cats.CategoryName
}).ToList();
for(var i=0;i<listCat.Count;i++)
{
cboCat.Items.Add(listCat[i]);
}
cboCat.ValueMember = "CategoryID";
cboCat.DisplayMember = "CategoryName";
}