[英]Set fixed Values in a NumericUpDown control
與為NumericUpDown
設置最小值和最大值相反,如何使用戶僅在不同的Preset Values之間進行選擇? (例如5、8、10、15、20、25)。
編輯:我可以通過1)單擊numericUpDown的箭頭和2)用鍵盤手動更改Value來區分ValueChanged事件嗎?
由於控件本身不支持此功能,因此您必須手動處理它。 將方法附加到ValueChanged
事件,並檢查該值是否為其中之一。 如果不是,則進行適當調整。
如果允許的值至少相隔兩個值,則可以輕松檢查它是向上還是向下,並且不需要存儲先前的值來確定該值。
由於這些值不是連續的,因此NumericUpDown可能不是此用例的正確控件。
如果您只有六個左右的值,那么組合框將是一個更好的選擇。
如果您有更多內容,那么帶有驗證的文本框可能會更好。
如果您確實是在NumericUpDown控件上設置的,那么就像其他人指出的那樣,您將需要進入ValueChanged事件並在那里進行驗證。
嘗試:
Public Class Form1
' NumericUpDown1
'.Minimum = 1
'.Maximum = 64
'.Increment = 1
'.value = 4
Dim NumList() As Integer = {1, 2, 4, 8, 16, 32, 64} ' list of admitted values
Dim NumExValue As Integer = 4 ' put the default value on numericUpDown
Dim NumDoChange As Boolean = True ' used for not looping in changeValue event
Private Sub NumericUpDown1_ValueChanged(sender As Object, e As EventArgs) Handles NumericUpDown1.ValueChanged
' if the event is calling from this event (when set .value) do nothing
If (NumDoChange = False) Then Exit Sub
With NumericUpDown1
Dim cv As Integer = .Value
' if no change (possible?) do nothing
If (cv = NumExValue) Then Exit Sub
' if the value IS on array do nothing
Dim ix As Integer = Array.IndexOf(NumList, cv)
If (ix >= 0) Then
NumExValue = cv
Exit Sub
End If
' if precedent value is 8 and up arrow pressed
' the current value is 9 so i search the index in array of
' value -1 and i take next element
If (cv > NumExValue) Then ' up arrow
ix = Array.IndexOf(NumList, cv - 1) + 1 ' get next element
NumDoChange = False ' stop ValueChanged event
.Value = NumList(ix) ' here start a call to this event
NumDoChange = True ' reset ValueChange event on
End If
' the same but precedent element
If (cv < NumExValue) Then ' down arrow pressed
ix = Array.IndexOf(NumList, cv + 1) - 1
NumDoChange = False
.Value = NumList(ix)
NumDoChange = True
End If
NumExValue = .Value
End With
End Sub
End Class
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.