[英]C# Linq - Combobox not filled
我對comboBoxContainer
有問題。 填充comboBoxategory
和comboBoxMarket
,不填充comboBoxContainer
。
selected.Container
具有正確的變量,但組合框未獲取此變量。
private void listBoxProducts_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
ProductList_Variables selected = ProductList_Variables)listBoxProducts.SelectedItem;
textBoxProduct.Text = selected.Product;
comboBoxCategory.SelectedItem = selected.Category;
comboBoxMarket.SelectedItem = selected.Market;
comboBoxContainer.SelectedItem = selected.Container;
textBoxPrice1.Text = selected.Price.ToString();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
class ProductList_Variables
{
public int Id { get; set; }
public string Product { get; set; }
public string Category { get; set; }
public string Size { get; set; }
public string Market { get; set; }
public string ProductName { get { return Product + " - " + Category + " - Size: " + Size +", Market: "+ Market; } }
public string Flavour { get; set; }
public decimal Price { get; set; }
public string Container { get; set; }
public int IdContainer { get; set; }
}
void Fillcombo()// is filling the combobox
{
try
{
using (var db = new GelatoProjectDBEntities())
{
var products = (from x in db.ProductsLists
select new ProductList_Variables { Id = x.Id, Product = x.Product, Category = x.Category, Size = x.Size, Market = x.Market, Container=x.Container, Price=x.Price, IdContainer=x.IdContainer }
).OrderBy(c => c.Product).ToArray();
listBoxProducts.Items.AddRange(products);
listBoxProducts.DisplayMember = "ProductName";
listBoxProducts.ValueMember = "Id";
var goods = (from x in db.Goods
select new ProductList_Variables { Id = x.Id, Product=x.item, Container = x.item}
).OrderBy(c => c.Product).ToArray();
comboBoxContainer.Items.AddRange(goods);
comboBoxContainer.DisplayMember = "Product";
comboBoxContainer.ValueMember = "Id";
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
看來您的comboBoxContainer充滿了對象,而不是字符串,因此分配時應該匹配該對象。
嘗試更換線
comboBoxContainer.SelectedItem = selected.Container;
如下
comboBoxContainer.SelectedItem =
comboBoxContainer.Items.OfType<ProductList_Variables>().SingleOrDefault(x => x.Container == selected.Container);
當屬性容器包含值(comboBoxContainer的數據元素的屬性ID)時,可以使用
comboBoxContainer.SelectedValue = selected.Container;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.