2016-05-03 11 views
0

私は(バランス、転送、メソッドを撤回)BankAccountクラスのインスタンスが含まれている私のリストボックス内のオブジェクトを持っているとWalletクラス(名前、誕生日など)を選択したリストボックス項目のオブジェクト情報を取得します。選択されたリストボックスオブジェクト(lbAccounts)についての情報の一部(残高など)。リストボックスで<br> が、私は表示する必要が

オブジェクト:

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); 

QUESTION:はどのように選択したリストボックスオブジェクトのバランスを得るのですか?

+0

WPF? WebForms? WinForms? ASP.NET MVC? ...? –

+0

選択したリストボックスオブジェクトの結果を[BankAccount]のタイプに解析/キャストしますか? – Hexie

+0

ウェブフォーム、C#とVS 2015 – Thisone

答えて

4

リストボックスの選択項目からオブジェクトを取得します。

BankAccount ba = lbAccounts.SelectedItem as BankAccount; 

私はあなたに役立つことを願っています。

BankAccount currentAccount= lbAccounts.SelectedItem as BankAccount; 

をしかし、私はあなたがBankAccountのリストを作成し、このリストを使用して、リストボックスをバインドすることを好む:

+0

それはすばらしく機能します。ありがとうございました。 – Thisone

1

あなたは、単に以下の操作を使用して、それをキャストすることができます。あなたは簡単にリストから選択した項目を取ったことができるように下記のコードを検討:

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(); 

をSO結合部分今、我々はのSelectedItemによるバックリストボックスからビジネス・オブジェクトを取得する必要がある上

IList<BankAccount> boundList = (IList<BankAccount>)lbAccounts.DataSource; 
BankAccount currentAccount= boundList[lbAccounts.SelectedIndex]; 
1

選択したリストボックスをBankAccountオブジェクトにキャストしてから、必要に応じてプロパティを使用します。

var balance = ((BankAccount)lbAccounts.SelectedItem).Balance 

ボーナスMSDNのリンク:How to: Convert a ListBoxItem to a New Data Type

1

あなたは安全なListBoxSelectedItemプロパティをキャストすることができます。

ただし、SelectedItemnullでないことを確認してください。選択された項目がリストにない場合、このプロパティはnullになります。

var selected = listBox1.SelectedItem as Account; 
if (selected != null) 
; // use it 
関連する問題