Looking at the provided code, I think that you are still struggling with its design. Currently, you have a class that contains four items. And you create a variable of that class that should hold a selected item. Doing so, you create a selected item that contains four items...
Furthermore, your code only uses String
s. I don't see any code related to dates or your NumericUpDown
and DateTimePicker
controls. It's difficult to reason about the logic with such differences. I'll try to focus on the actual question about a numeric up/down control and the collection that should store dates depending on the up/down control's selected value.
Let me assume the following requirements:
- It should be possible to store up to four values (dates) in a collection (like an array or a dictionary).
- The user should be able to select a specific entry in the collection (using a
NumericUpDown
) and modify its value (using a DateTimePicker
).
You probably do not need a specific class for your items (yet), so you could actually drop your my_Class
class.
I would choose a Dictionary
here to store the date values:
Dim items As New Dictionary(Of Integer, Date)
You can then get the date from the dictionary like this:
Public Sub showItem(key As Integer)
If items.ContainsKey(key) Then
Dim dateValue As Date = items(key)
If DateTimePicker1.ShowCheckBox Then
DateTimePicker1.Checked = True
End If
DateTimePicker1.Value = dateValue
Else
If DateTimePicker1.ShowCheckBox Then
DateTimePicker1.Checked = False
End If
DateTimePicker1.Value = Nothing '"Nothing" actually represents a default value, so it "works" for value types and structures (like dates) as well. :)
End If
End Sub
Note that I changed showItem
's parameter's type to Integer
. The Value
of a NumericUpDown
control is of type Decimal
, and since you will probably use it for integer values 1 to 4, you could cast that Value
to an Integer
and pass it to showItem
. (I assume you want to call the showItem
method inside your NumericUpDown
control's ValueChanged
event.)
Private Sub NumericUpDown1_ValueChanged(sender As Object, e As EventArgs) Handles NumericUpDown1.ValueChanged
Dim key as Integer = CInt(NumericDropDown1.Value)
showItem(key)
End Sub
This example only shows you how to read values from your dictionary. Depending on what you actually want to do, you need to shape the logic in the showItem
method. And several other methods as well. I would at least expect that you want to implement an event handler that is triggered when your DateTimePicker
's value is changed; it should store the selected date in the dictionary. Something like this:
Private Sub DateTimePicker1_ValueChanged(sender As Object, e As EventArgs) Handles DateTimePicker1.ValueChanged
Dim key As Integer = CInt(NumericUpDown1.Value)
If DateTimePicker1.Checked Then
items(key) = DateTimePicker1.Value
Else
items.Remove(key);
End If
showItem(key)
End Sub