2

我有一个数据绑定组合框 (WinForms),当组合框失去焦点时,它显示 ValueMember,而不是 DisplayMember。这是我遇到此问题的一个简单示例:

Public Class Populator

    Public Class Job
        Property JobID As Integer
        Property JobName As String

        Public Sub New(ByVal id As Integer, ByVal name As String)
            JobID = id
            JobName = name
        End Sub
    End Class

    Public Class Person
        Property Name As String
        Property JobID As Integer

        Public Sub New(ByVal n As String, ByVal id As Integer)
            Name = n
            JobID = id
        End Sub
    End Class

    Public Shared Function GetJobs() As List(Of Job)
        Dim joblist As New List(Of Job)
        joblist.Add(New Job(1, "Manager"))
        joblist.Add(New Job(2, "Clerk"))
        joblist.Add(New Job(3, "Unemployed"))
        Return joblist
    End Function

    Public Shared Function GetPeople() As List(Of Person)
        Dim personList As New List(Of Person)
        personList.Add(New Person("Bill", 2))
        personList.Add(New Person("Sally", 1))
        personList.Add(New Person("Mark", 3))
        personList.Add(New Person("Angie", 3))
        personList.Add(New Person("Phil", 2))
        Return personList
    End Function

End Class

Public Class Form1

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Me.Populator_PersonBindingSource.DataSource = Populator.GetPeople
        Me.JobBindingSource.DataSource = Populator.GetJobs

    End Sub

End Class

以下是一些截图:

使用数据绑定设计器

选择项目时

失去焦点后

当组合框失去焦点时,请就如何保持 DisplayMember 的显示给我建议。

4

2 回答 2

0

必须将 ComboBox DropDownStyle 设置为 DropDownList,而不是 DropDown,以消除这种失焦行为。显然,当您将字段作为 ComboBox 从 Data Sources 选项卡中拖动时,ComboBox DropDownStyle 最初设置为 DropDown。

我在上面列出的示例程序和我的真实程序中尝试了这个。它在两种情况下都有效。

于 2013-06-12T19:36:36.737 回答
-1

所以不要使用视觉辅助使用sql代码,在cs代码中填充

       //when you set data source it loses focus to window title
        cmb.datasource = datatable;
        cmb.valueMember = "col1";
        cmb.dispMember = "col2";

        // this does the trick. gives focus back into combobox's list 
        cmb.DropDownStyle = ComboBoxStyle.DropDownList; 
        cmb.DropDownStyle = ComboBoxStyle.DropDown;
于 2016-01-13T08:30:40.620 回答