使用组合框

时间:2017-09-29 08:07:28

标签: c# winforms list combobox textbox

您好我在win表单中显示我的数据时遇到问题。我有一个sql数据库,我把表放在一个列表中:

  public List<ItemsForSale> GetStock()
        {
            var db = new Model1();
            return db.Stock.ToList();
        }

我使用所选值填充我的组合框,但只显示其中一列(股票名称),其他列是库存金额和股票价格。

   Stock stock = new Stock();

   comboBox1.DataSource = stock.GetStock().Select(x => x.StockName).ToList();

如何在其他文本框中显示行数据。例如,如果我选择库存Pasta,我如何在文本框中显示它的价格。

1 个答案:

答案 0 :(得分:0)

以下是一个示例,您正在寻找组合框的selectedIndex_Changed事件。

我有一个Stock实体,

public class Stock {
       public Stock(int Id,string Name,decimal Price) {
           this.Id = Id;
           this.Name = Name;
           this.Price = Price;
       }
       public int Id { get; set; }
       public string Name { get; set; }
       public decimal Price { get; set; }
}


List<Stock> dataSource = new List<Stock>(); // set list of object to an variable not to query db again and again, just use this all the time
private void Form1_Load(object sender, EventArgs e) {
      dataSource = GetStocks(); 
      comboBox1.DisplayMember = "Name"; // set display member
      comboBox1.ValueMember = "Id"; // value member as Id to use at selectedIndex changed
      comboBox1.DataSource = dataSource;
}
public List<Stock> GetStocks() { // just creating on my own list, you won't change this
     return new List<Stock>() { new Stock(1,"test1",13) , new Stock(2, "test2", 17), new Stock(3, "test3", 113) };
}

private void comboBox1_SelectedIndexChanged(object sender, EventArgs e) {
     // query your List variable to find the stock by selected Item's Id, get first one and take Price property
      decimal value = dataSource.Where(x => x.Id == (int)comboBox1.SelectedValue).FirstOrDefault().Price; 
      textBox1.Text = value.ToString(); // set value to textbox
}

希望有所帮助,