【问题标题】:Databound combobox displays valuemember when it loses focus数据绑定组合框在失去焦点时显示 valuemember
【发布时间】:2013-06-08 23:27:36
【问题描述】:

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

【问题讨论】:

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


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

      所以不要使用视觉辅助使用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;
      

      【讨论】:

      • 纯代码答案并不是特别有用。请解释您的代码是如何工作的,并告诉我们这如何回答所发布的问题。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-11-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多