- UID
- 70738
- 帖子
- 459
- 主題
- 37
- 精華
- 0
- 積分
- 474
- 楓幣
- 2365
- 威望
- 110
- 存款
- 1576
- 贊助金額
- 1300
- 推廣
- 0
- GP
- 68
- 閱讀權限
- 150
- 性別
- 男
- 在線時間
- 784 小時
- 註冊時間
- 2014-7-15
- 最後登入
- 2024-11-16
|
本帖最後由 s860070 於 2015-8-28 16:19 編輯
CInt是把數值轉換成整數,但是遇到非數值字串將會錯誤
Val是將數值字串轉換成數值(空的會轉換成0)
你要不要改成Function 比較好維護跟擴充介面呀?
完整程式碼:
Public Function 累加(ByVal 開始值 As Integer, ByVal 結束值 As Integer) As Long
Dim i As Long = 0
Dim Sum As Long = 0
For i = 開始值 To 結束值 Step 1
Sum += i
Next
Return Sum
End Function
Private Sub Btn_Calculate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Btn_Calculate.Click
Dim 開始值 As Integer = Val(Txt_Start.Text)
Dim 結束值 As Integer = Val(Txt_Stop.Text)
Txt_Final.Text = "從 " & 開始值 & " 加到 " & 結束值 & " = " & 累加(開始值, 結束值)
End Sub
Private Sub Txt_Start_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles Txt_Start.KeyPress
'禁止0~9和BackSpace以外的值輸入
If InStr("0123456789" & Chr(8), e.KeyChar) = 0 Then e.KeyChar = ""
End Sub
Private Sub Txt_Stop_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles Txt_Stop.KeyPress
'禁止0~9和BackSpace以外的值輸入
If InStr("0123456789" & Chr(8), e.KeyChar) = 0 Then e.KeyChar = ""
End Sub
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'結果唯讀
Txt_Final.ReadOnly = True
'TextBox的文字置中
Txt_Start.TextAlign = HorizontalAlignment.Center
Txt_Stop.TextAlign = HorizontalAlignment.Center
Txt_Final.TextAlign = HorizontalAlignment.Center
End Sub
|
|