Вот как я могу реализовать упражнение:
Option Strict On
Option Explicit On
Public Class frmMain
Private ReadOnly _labelOriginalPrice, _labelDiscounts, _labelDiscountAmount, _labelFinalPrice As Label
Private ReadOnly _textboxOriginalPrice, _textboxDiscountAmount, _textboxFinalPrice As TextBox
Private ReadOnly _buttonCalculate As Button
Private ReadOnly _listboxDiscounts As ListBox
Private readonly _discounts As Dictionary(Of Double, String)
Public Sub New()
InitializeComponent()
'Setup the Form and the controls
Me.Font = New Font(FontFamily.GenericSansSerif, 10, FontStyle.Regular, GraphicsUnit.Pixel)
_discounts = New Dictionary(Of Double, String)() From {
{0.1, "10%"},
{0.15, "15%"},
{0.2, "20%"},
{0.25, "25%"},
{0.3, "30%"},
{0.35, "35%"},
{0.4, "40%"}
}
_labelOriginalPrice = New Label() With {
.Font = Me.Font,
.Location = New Point(5, 5),
.Text = "Original Price: "
}
_textboxOriginalPrice = New TextBox() With {
.Font = Me.Font,
.Left = _labelOriginalPrice.Right + 5,
.Top = _labelOriginalPrice.Top,
.Width = Me.ClientSize.Width \ 2 - 15
}
_labelDiscounts = New Label() With {
.Font = Me.Font,
.Left = _labelOriginalPrice.Left,
.Text = "Discounts: ",
.Top = _labelOriginalPrice.Bottom + 5
}
_listboxDiscounts = New ListBox() With {
.DataSource = new BindingSource(_discounts, Nothing),
.DisplayMember = "Value",
.Font = Me.Font,
.Left = _labelDiscounts.Right + 5,
.Top = _labelDiscounts.Top,
.Width = _textboxOriginalPrice.Width,
.ValueMember = "Key"
}
_labelDiscountAmount = New Label() With {
.Font = Me.Font,
.Left = _textboxOriginalPrice.Right + 5,
.Text = "Discounted Amount: ",
.Top = _labelOriginalPrice.Top
}
_textboxDiscountAmount = New TextBox() With {
.Enabled = False,
.Font = Me.Font,
.Left = _labelDiscountAmount.Left,
.Top = _labelDiscountAmount.Bottom + 5,
.Width = Me.ClientSize.Width - 5 - .Left
}
_labelFinalPrice = New Label() With {
.Font = Me.Font,
.Left = _labelDiscountAmount.Left,
.Text = "Final Price: ",
.Top = _textboxDiscountAmount.Bottom + 5
}
_textboxFinalPrice = New TextBox() With {
.Enabled = False,
.Font = Me.Font,
.Left = _labelDiscountAmount.Left,
.Top = _labelFinalPrice.Bottom + 5,
.Width = _textboxDiscountAmount.Width
}
_buttonCalculate = New Button() With {
.Enabled = False,
.Font = Me.Font,
.Left = _labelFinalPrice.Left,
.Text = "Calculate",
.Top = _textboxFinalPrice.Bottom + 5
}
_listboxDiscounts.Height = _buttonCalculate.Bottom - _listboxDiscounts.Top
Me.Controls.AddRange({_labelOriginalPrice, _textboxOriginalPrice, _labelDiscounts, _listboxDiscounts, _labelDiscountAmount, _textboxDiscountAmount, _labelFinalPrice, _textboxFinalPrice, _buttonCalculate})
Me.AcceptButton = _buttonCalculate
'Bind the control events
AddHandler _textboxOriginalPrice.TextChanged, AddressOf InputChanged
AddHandler _listboxDiscounts.SelectedIndexChanged, AddressOf InputChanged
AddHandler _buttonCalculate.Click, AddressOf Calculate
End Sub
Private Sub frmMain_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
End Sub
Private Sub InputChanged(ByVal sender As Object, ByVal e As EventArgs)
' Make sure that:
' A) the user entered a valid double in the textbox
' B) that the user selected an item in the listbox
Dim validNumericInput As Boolean = Double.TryParse(_textboxOriginalPrice.Text, Nothing)
Dim listboxValueSelected As Boolean = _listboxDiscounts.SelectedIndex <> -1
' Toggle the button based on the conditions outlined above
_buttonCalculate.Enabled = validNumericInput AndAlso listboxValueSelected
End Sub
Private Sub Calculate(ByVal sender As Object, ByVal e As EventArgs)
' Get the original price and the discount from their respective controls
' We can safely assume that the values will be valid doubles because of:
' A) the Double.TryParse on _textboxOriginalPrice in the InputChanged method
' B) we've bound _listboxDiscounts to a type safe Dictionary
Dim originalPrice As Double = Convert.ToDouble(_textboxOriginalPrice.Text)
Dim discountPerentage As Double = Convert.ToDouble(_listboxDiscounts.SelectedValue)
' Do the actual calculations
Dim discountPrice As Double = originalPrice * discountPerentage
Dim finalPrice As Double = originalPrice - discountPrice
' Display the calculations
' The "C" format indicates that we want to display the output as currency
_textboxDiscountAmount.Text = discountPrice.ToString("C")
_textboxFinalPrice.Text = finalPrice.ToString("C")
End Sub
End Class
Я настраиваю элементы управления с помощью кода, чтобы вы могли видеть имена элементов управления и их свойства, но это не обязательно.Вы можете сделать все от первого Private ReadOnly ...
до конструктора формы через конструктор форм, за исключением:
- Объявление и инициализация переменной
_discounts
- Установка следующего ListBoxсвойства:
- Источник данных
- DisplayMember
- ValueMember
- Код под
'Bind the control events
комментарием
Я пытался часто комментировать свой код, чтобы объяснить, как и почему код работает.Надеюсь, это работает для вас, и если у вас есть какие-либо вопросы, не стесняйтесь спрашивать.