C#银行账户存款
本文关键字: | 更新日期: 2023-09-27 18:26:45
大家好,我有一个银行账户项目,当用户选择索引时,它会显示账户信息。此信息包括帐户的当前余额。然后我还有存款模拟,我的存款金额加起来应该是当前余额。我不明白它为什么不做这项工作。
我有这个代码,用于我选择的索引,它可以提取帐户信息。
private void accountNumComboBox_SelectedIndexChanged(object sender, EventArgs e)
{
if (accountNumComboBox.SelectedIndex == 0)
{
ownerIdLabel.Text = "0001";
balanceLabel.Text = savings1.Balance.ToString("c");
interestLabel.Text = (string.Format("{0}%", savings1.Interest));
interestRLabel.Text = "Interest Rate:";
}
我有这个存款按钮的代码
private void depositButton_Click(object sender, EventArgs e)
{
decimal amount;
if (decimal.TryParse(depositTextBox.Text, out amount))
{
account.Deposit(amount);
account.Balance += amount;
depositTextBox.Clear();
}
else
{
MessageBox.Show("Pls enter valid amount.");
}
}
我输入的金额加起来不等于余额标签中的当前余额。文本非常感谢你的帮助。
编辑:我在我的银行账户类中也有这个
public decimal Balance
{
get { return _balance; }
set { _balance = value; }
}
public BankAccount(decimal intialBalance, string ownerId, string accountNumber)
{
_balance = intialBalance;
_customerId = ownerId;
_accountNumber = accountNumber;
}
public void Deposit(decimal amount)
{
if ( amount>0)
_balance += amount;
else
throw new Exception("Credit must be > zero");
}
public void Withdraw(decimal amount)
{
_balance -= amount;
}
您的存款按钮事件处理程序没有更改余额标签的代码。
private void depositButton_Click(object sender, EventArgs e)
{
decimal amount;
if (decimal.TryParse(depositTextBox.Text, out amount))
{
account.Deposit(amount);
account.Balance += amount;
depositTextBox.Clear();
balanceLabel.Text = account.Balance.ToString("c"); // This line added
}
else
{
MessageBox.Show("Pls enter valid amount.");
}
}
编辑:
使用您的代码
private BankAccount account;
private void accountNumComboBox_SelectedIndexChanged(object sender, EventArgs e)
{
if (accountNumComboBox.SelectedIndex == 0)
{
account = (BankAccount) savings1;
}
updateUi();
}
private void updateUi() {
ownerIdLabel.Text = "0001";
balanceLabel.Text = account.Balance.ToString("c");
interestLabel.Text = (string.Format("{0}%", account.Interest));
interestRLabel.Text = "Interest Rate:";
}
private void depositButton_Click(object sender, EventArgs e)
{
decimal amount;
if (decimal.TryParse(depositTextBox.Text, out amount))
{
account.Deposit(amount);
account.Balance += amount;
depositTextBox.Clear();
balanceLabel.Text = account.Balance.ToString("c"); // This line added
}
else
{
MessageBox.Show("Pls enter valid amount.");
}
}
注意:以上编辑是基于您给出的代码。你可能需要稍微修改一下以适应你的目标。另外,请注意,您实际上对ownerId文本进行了硬编码。
在您的存款程序中,您正在更改余额:
_balance += amount;
然而,在您的存款Button_Click例程中,您也在更改余额:
account.Deposit(amount);
account.Balance += amount;
你不需要修改这里的余额,因为存款已经可以了。