【问题标题】:Selected Value for combobox not working for DirectCast or CType组合框的选定值不适用于 DirectCast 或 CType
【发布时间】:2018-03-07 04:41:47
【问题描述】:

我试图清除表单上对组合框的选择,但是当将 .SelectedValue 属性设置为 -1 时,我得到的是第一个值。

为了解释headerControlscontrolsList,我在运行时从配置文件创建所有控件,加载到controlsList,当我将控件添加到屏幕时,我还将它添加到headerControls

Public headerControls As New Dictionary(Of String, Control)

Try
    For each dynamicControl As KeyValuePair(Of Integer, CustomControl) In controlsList 
        Select dynamicControl.Value.ControlType.ToLower()
            Case "textbox"
                DirectCast(headerControls.Item(dynamicControl.Value.ControlName), TextBox).Text = ""
            Case "combobox"
                DirectCast(headerControls.Item(dynamicControl.Value.ControlName), ComboBox).SelectedValue = -1
        End Select
    Next
Catch ex As Exception
        'Error Handling
End Try

创建控件的代码:

Try
    For each dynamicControl As KeyValuePair(Of Integer, CustomControl) In controlsList 

        Select Case dynamicControl.Value.ControlType.ToLower()
            Case "textbox"
                Dim textBoxControl As New TextBox

                With textBoxControl
                    'Set Textbox properties here
                End With

                headerControls.Add(dynamicControl.Value.ControlName, textBoxControl)
                Controls.Add(textBoxControl)

            Case "combobox"
                Dim comboBoxControl As New ComboBox

                With comboBoxControl
                    'Set ComboBox properties here
                End With

                LoadCombo(comboBoxControl)

                headerControls.Add(dynamicControl.Value.ControlName, comboBoxControl)
                Controls.Add(comboBoxControl)

        End Select
    Next

Catch ex As Exception
    'Error Handling
End Try

清除文本框有效,但 ComboBox 显示的行为与我将文本框放在屏幕上并使用 .SelectedValue = -1

的行为不同

【问题讨论】:

    标签: vb.net combobox controls


    【解决方案1】:

    也许您应该检查SelectedValueSelectedIndex 之间的区别。将SelectedValue 设置为一个值不可能选择任何项目。如果您不想选择任何项目,则将SelectedIndex 设置为-1,将SelectedItem 设置为Nothing,或者,根据您的绑定,将SelectedValue 设置为Nothing

    【讨论】:

    • 我尝试了 SelectedItem 并收到相同的结果,但如果我这样做了两次,它会清除选择...虽然不完全确定为什么
    猜你喜欢
    • 1970-01-01
    • 2011-03-04
    • 2022-11-11
    • 2010-12-06
    • 2021-07-14
    • 2011-02-11
    • 2021-02-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多