我的列表框中有对象,其中包含BankAccount
类的实例(余额,转移,提取方法)和Wallet
类(名称,生日等)
我需要查看有关所选列表框对象(lbAccounts)的某些信息部分(如余额)。
列表框中的对象:
DateTime birth = Convert.ToDateTime("01/01/1970");
Wallet account = new Wallet("Bob", "Smith", birth);
BankAccount account1 = new BankAccount(account);
account1.DepositFunds(5000);
BankAccount account2 = new BankAccount(account);
account2.DepositFunds(300);
//Adding accounts to listbox
lbAccounts.Items.Add(account1);
lbAccounts.Items.Add(account2);
问题:如何获取所选列表框对象的余额?
答案 0 :(得分:5)
您将从列表框的选定项目中获取对象。
BankAccount ba = lbAccounts.SelectedItem as BankAccount;
我希望它会对你有所帮助。
答案 1 :(得分:1)
您只需使用以下操作即可投射:
BankAccount currentAccount= lbAccounts.SelectedItem as BankAccount;
但我更喜欢你创建一个BankAccount
列表并使用此列表绑定列表框。这样您就可以轻松地从列表中选择所选项目:考虑以下代码:
List<BankAccount> AccountList= new List<BankAccount>();
AccountList.Add(new BankAccount(){fName="Bob", lName="Smith", dob=birth });
AccountList.Add(new BankAccount(){fName="foo", lName="bar", dob=birth });
//Populate the list here
// Bind the list box according to the type of application you are using
// here i use asp.net
lbAccounts.DataTextField = "fName";
lbAccounts.DataValueField = "fName";
lbAccounts.DataBind();
现在绑定部分结束了我们需要根据selectedItem从Listbox中获取业务对象
IList<BankAccount> boundList = (IList<BankAccount>)lbAccounts.DataSource;
BankAccount currentAccount= boundList[lbAccounts.SelectedIndex];
答案 2 :(得分:1)
将选定的列表框投射到BankAccount
对象 - 然后根据需要使用这些属性。
var balance = ((BankAccount)lbAccounts.SelectedItem).Balance
Bonus MSDN链接:How to: Convert a ListBoxItem to a New Data Type
答案 3 :(得分:1)
您可以安全地投射SelectedItem
的{{1}}属性。
但请确保ListBox
不是SelectedItem
。如果列表中没有选定的项目,则此属性将为null
。
null