[英]Banking Application - Calling from a class to a windows form in c#
我在C#中學習Windows窗體,發現很難理解使用窗體和類。 我正在創建銀行業務應用程序,希望用戶能夠:按下按鈕以查看其當前余額,輸入借記金額(取出資金)其帳戶,獲得成功注釋,或者如果沒有,則顯示警告注釋足夠的資金和余額來更新。
我不明白如何將帳戶類連接到表單和指定的標簽和按鈕。 在過去的幾個小時里,我剛開始嘗試不同的方法,但是一無所獲。 有人可以解釋一下當按下按鈕時我將如何在標簽框中顯示余額為500。 另外,我如何通過在文本框中輸入金額並按下按鈕來借記帳戶。 然后將便箋寫到確認借記的標簽上。 我班上有“資金不足”的信息,但理想情況下,我希望以表格的形式填寫,因為我聽說過這樣更好的做法。
我希望我已經足夠清楚了,但是會證實一切! 我在這里尋求很多幫助,因為我是Windows窗體的新手,但是任何幫助或指導都將不勝感激!
class AccountClass
{
private decimal balance = 500;
public AccountClass(decimal myBalance)
{
Balance = myBalance;
}
public virtual bool Debit(decimal amount)
{
if (amount > Balance)
{
Console.WriteLine("There is not enough money in your account");
return false;
}
else
{
Balance = Balance - amount;
return true;
}
}
形成:
//button to see balance
private void btnAccountSeeBalance_Click(object sender, EventArgs e)
{
//label balance should print to
lblAccountBalance.Text = myBalance.ToString();
}
//button to debit account
private void btnAccountDebit_Click(object sender, EventArgs e)
{
//text box to enter amount to debit
txtAccountDebitAmount
//label to print confirm/insufficient funds to
lblAccountDebitSuccess
}
您的Account
類不應直接在表單中調用任何內容。 讓您的Account類生成事件或使用函數的返回值。 您的Windows窗體應該在Account類中創建和調用函數,然后在視圖中處理響應。 Account類不應具有有關視圖/表單的線索。
單擊事件的簡單實現:
private void btnAccountDebit_Click(object sender, EventArgs e)
{
var ac = new AccountClass( balance);
var rtn = ac.Debit( amount);
}
這應該可以幫助您入門。 您希望將所有帳戶邏輯都保留在Account類的內部,並將所有消息或用戶界面邏輯保留在窗體和UI中,而不是在Account類內部。
public partial class Form1 : Form
{
private AccountClass account;
public Form1()
{
InitializeComponent();
account = new AccountClass(500);
}
public class AccountClass
{
public Decimal Balance
{
get;
private set;
}
public AccountClass(decimal initialBalance)
{
Balance = initialBalance;
}
public void Debit(decimal amount)
{
if (amount > Balance)
throw new InsufficientFundsException();
Balance -= amount;
}
}
public class InsufficientFundsException : Exception { }
private void btnGetBalance_Click(object sender, EventArgs e)
{
txtBalance.Text = account.Balance.ToString();
}
private void btnDebit_Click(object sender, EventArgs e)
{
Decimal debitAmount;
try
{
debitAmount = Decimal.Parse(txtAmount.Text);
}
catch (Exception)
{
MessageBox.Show("Amount is not valid");
return;
}
try
{
account.Debit(debitAmount);
MessageBox.Show(debitAmount + " has been debited from your account");
}
catch (InsufficientFundsException)
{
MessageBox.Show("There were insufficient funds. Your current account balance is " + account.Balance);
}
}
}
我所做的就是創建一個Form並在其上拖動2個TextBoxes和Buttons。 如果將它們命名為txtBalance和txtAmount以及btnGetBalance和btnDebit並將它們連接到click事件,則可以使用此代碼。
編輯:
為了簡潔起見,我將所有代碼都放在Form類中。 但是顯然那些額外的類應該是單獨的代碼文件。 考慮一下我所說的關於分離UI和帳戶邏輯的內容。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.