VB.NET存提功能问题排查及代码分层实现咨询
Let's break down your problems and refactor your code step by step, like we're troubleshooting together:
1. Why Isn't the MsgBox Showing Up?
Ah, here's a classic Web Forms gotcha: MsgBox() is a WinForms-only method. When you call it in a web app, it runs on the server (not your user's browser)—so even if your condition is true, your users will never see that pop-up.
Instead, you need to send a client-side JavaScript alert() to the browser. Replace all your MsgBox calls with this:
ClientScript.RegisterStartupScript(Me.GetType(), "AlertID", "alert('Your message here');", True)
For your empty fields check, that becomes:
ClientScript.RegisterStartupScript(Me.GetType(), "MissingInfo", "alert('Please enter Information');", True)
2. Fixing String-Based Amount Calculations
Right now, you're treating TextBox.Text values as strings, which means += is concatenating text instead of adding numbers (and -= will throw a compile error with Option Strict On—which you have enabled, great call!).
To fix this, we'll convert the text to Decimal (the best type for currency) before doing math, then convert back to a string for display:
Private Sub doConfirm() Dim amount As Decimal Dim currentBalance As Decimal = 0 ' First, validate the amount is a valid number If Not Decimal.TryParse(txtAmount.Text, amount) Then ClientScript.RegisterStartupScript(Me.GetType(), "InvalidAmount", "alert('Please enter a valid numeric amount');", True) Return End If ' Handle empty balance (default to 0 if blank) Decimal.TryParse(txtBalance.Text, currentBalance) If rbtndeposit.Checked Then currentBalance += amount txtBalance.Text = currentBalance.ToString("C") ' Format as currency for readability ElseIf rbtnWithdraw.Checked Then If amount <= currentBalance Then currentBalance -= amount txtBalance.Text = currentBalance.ToString("C") Else ClientScript.RegisterStartupScript(Me.GetType(), "InsufficientFunds", "alert('Funds not sufficient');", True) End If End If End Sub
3. Refactoring to a Separate Class for Business Logic
To keep your code clean and maintainable, let's move the deposit/withdraw logic into a dedicated class—this separates UI code from business rules, making it easier to test and reuse later.
Step 1: Create the Account Service Class
Add a new class (e.g., AccountService.vb) to your project:
Public Class AccountService Public Function Deposit(currentBalance As Decimal, amount As Decimal) As Decimal If amount <= 0 Then Throw New ArgumentException("Deposit amount must be positive.") End If Return currentBalance + amount End Function Public Function Withdraw(currentBalance As Decimal, amount As Decimal) As Decimal If amount <= 0 Then Throw New ArgumentException("Withdrawal amount must be positive.") End If If amount > currentBalance Then Throw New InvalidOperationException("Insufficient funds.") End If Return currentBalance - amount End Function End Class
Step 2: Update Your Page Class to Use the Service
Now modify your _Default class to call this service instead of handling logic directly:
Option Strict On Option Explicit On Public Class _Default Inherits System.Web.UI.Page ' Create an instance of our service class Private _accountService As New AccountService() Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load If Not IsPostBack Then lblFirstName.Focus() End If End Sub Protected Sub btnConfirm_click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnConfirm.Click ' Use AndAlso instead of And for faster short-circuit checks If String.IsNullOrEmpty(txtFirstName.Text) AndAlso String.IsNullOrEmpty(txtLastName.Text) AndAlso String.IsNullOrEmpty(txtAmount.Text) Then ClientScript.RegisterStartupScript(Me.GetType(), "MissingInfo", "alert('Please enter Information');", True) Return End If Try Dim amount As Decimal Dim currentBalance As Decimal = 0 ' Validate amount input If Not Decimal.TryParse(txtAmount.Text, amount) Then ClientScript.RegisterStartupScript(Me.GetType(), "InvalidAmount", "alert('Please enter a valid numeric amount');", True) Return End If ' Parse current balance (default to 0 if empty) Decimal.TryParse(txtBalance.Text, currentBalance) If rbtndeposit.Checked Then currentBalance = _accountService.Deposit(currentBalance, amount) txtBalance.Text = currentBalance.ToString("C") ElseIf rbtnWithdraw.Checked Then currentBalance = _accountService.Withdraw(currentBalance, amount) txtBalance.Text = currentBalance.ToString("C") End If Catch ex As ArgumentException ClientScript.RegisterStartupScript(Me.GetType(), "InvalidInput", $"alert('{ex.Message}');", True) Catch ex As InvalidOperationException ClientScript.RegisterStartupScript(Me.GetType(), "InsufficientFunds", $"alert('{ex.Message}');", True) End Try End Sub End Class
Quick Bonus Tips:
- Use
AndAlsoinstead ofAndfor conditional checks—it short-circuits, which is more efficient. - Formatting the balance with
ToString("C")automatically adds currency symbols and proper decimal places for your users. - Adding validation for positive amounts prevents silly invalid transactions (like depositing $0).
内容的提问来源于stack exchange,提问作者Learner

