Winform 下拉框绑定问题
在Winform中下拉框绑定的时候只能读到text属性值,Id的值不管怎么搞都读取不到,所以就百度找到了一种方式:
public void CmdBind() { var data = _logic.GetCurrency();//数据源 if (!data.Any()) return; foreach (var currency in data) { cmdCurrencyName.Items.Add(new CurrencyItem { CurrencyName = currency.Description, CurrencyValue = currency.Id }); } } private void cmdCurrencyName_SelectedIndexChanged(object sender, EventArgs e) { var selectedItem = (CurrencyItem)cmdCurrencyName.SelectedItem; _model.Description = selectedItem.CurrencyName; _model.CurrencyId = selectedItem.CurrencyValue; }
添加一个类,定义下拉框滴text、Id属性:
public class CurrencyItem { public CurrencyItem() { } public CurrencyItem(int currencyValue, string currencyName) { CurrencyValue = currencyValue; CurrencyName = currencyName; } public int CurrencyValue { get; set; } public string CurrencyName { get; set; } public override string ToString() { return CurrencyName; } }