数据绑定组合框在失去焦点时显示值成员

时间:2013-06-12 18:16:27

标签: .net vb.net winforms data-binding combobox

我有一个数据绑定组合框(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

以下是一些截图:

Using databinding designer

While selecting item

After losing focus

请告诉我如何在组合框失去焦点时保持DisplayMember的显示。

2 个答案:

答案 0 :(得分:0)

ComboBox DropDownStyle必须设置为DropDownList,而不是DropDown,以消除这种离焦行为。显然,当您从“数据源”选项卡中将字段拖动为ComboBox时,ComboBox DropDownStyle最初设置为DropDown。

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

答案 1 :(得分:-1)

所以不要使用visual aid使用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;
相关问题