我的表单上有DropDown和DropDownList。我知道DropDown可以保存占位符文本而DropDownList不能;我想要一些代码或解决方法允许:
这可能吗?
感谢。
答案 0 :(得分:0)
但最好是带有占位符文本的DropDownList(或不是上下文菜单选项)
根据定义,此控件中显示的文本始终是所选项目的文本。如果需要,您可以在列表中添加“假”项(例如“选择属性代码”),但您必须检查以后是否未选择此项目。
要显示其中一个项目(假的或非假的),只需在加载列表后将SelectedIndex
设置为适当的值。
DropDown为只读,因此不允许用户键入
这将主动确保文本在列表中或默认值,有效地使其只读。 (为ComboBox编写,但行为应该与DropDown相同。)
Private Sub ComboBox1_TextChanged(sender As Object, e As EventArgs) Handles ComboBox1.TextChanged
Static recursion As Boolean = False
Dim defaultText As String = "My Default Text"
If recursion Then
recursion = False
Else
If ComboBox1.Items.Count > 0 Then
For i As Integer = 0 To ComboBox1.Items.Count - 1
If ComboBox1.Items(i).ToString = ComboBox1.Text Then
Exit Sub
End If
Next
recursion = True
ComboBox1.Text = defaultText
End If
End Sub
或者,只要“严格”的ComboBox失去焦点来完成同样的事情,这里就是一个子调用。不同之处在于,这样做可以让您保持自动完成功能:
Public Sub EnforceList(ByRef box As ComboBox) 'FORCES .TEXT TO BEST (OR FIRST) MATCH IN .ITEMS
'If list contains item whose name begins another item's, the shorter must be listed first, e.g. "sew" must preceed "sewer"
If box.Items.Count = 0 Then Exit Sub 'Can't enforce a list that doesn't exist
Dim txt As String = box.Text
Do
For i As Integer = 0 To box.Items.Count - 1
If box.Items(i).ToString Like txt & "*" Then
box.Text = box.Items(i).ToString
Exit Sub
End If
Next
txt = Left(txt, Len(txt) - 1)
Loop
End Sub