2009-12-11 7 views
5

Visual Basic 2010에서 콤보 상자에 각 항목의 데이터 값을 어떻게 추가 할 수 있습니까?콤보 상자 항목에 값을 추가하는 방법

html 드롭 다운 상자와 유사합니다.

또는 각 항목에 값을 추가 할 수 있습니까?

I는 다음과 같이 MySQL 데이터베이스에서 항목을 추가하고 :

Command = New MySqlCommand("SELECT * FROM `maillist` WHERE l_id = '" & id & "'", connection) 

Command.CommandTimeout = 30 
Reader = Command.ExecuteReader() 
If Reader.HasRows = True Then 
    While Reader.Read() 
     ComboBox1.Items.Add(Reader("name")) 
    End While 
End If 

내가 각 항목의 값으로 Reader("ID")을 추가 할 필요가 ...

답변

9

SelectedValue를 사용하려면 콤보 박스가 데이터 바인딩되어야합니다.

는 콤보를 설정하려면

ComboBox1.DataSource = GetMailItems() 
ComboBox1.DisplayMember = "Name" 
ComboBox1.ValueMember = "ID" 

데이터를 얻으려면 : 나는 당신이 윈도우 폼에 콤보 상자에 항목을 추가하고자하는 것을 가정하고

Function GetMailItems() As List(Of MailItem) 

    Dim mailItems = New List(Of MailItem) 

    Command = New MySqlCommand("SELECT * FROM `maillist` WHERE l_id = '" & id & "'", connection) 
    Command.CommandTimeout = 30 
    Reader = Command.ExecuteReader() 

    If Reader.HasRows = True Then 
     While Reader.Read() 
      mailItems.Add(New MailItem(Reader("ID"), Reader("name"))) 
     End While 
    End If 

    Return mailItems 

End Function 

Public Class MailItem 

    Public Sub New(ByVal id As Integer, ByVal name As String) 
     mID = id 
     mName = name 
    End Sub 

    Private mID As Integer 
    Public Property ID() As Integer 
     Get 
      Return mID 
     End Get 
     Set(ByVal value As Integer) 
      mID = value 
     End Set 
    End Property 

    Private mName As String 
    Public Property Name() As String 
     Get 
      Return mName 
     End Get 
     Set(ByVal value As String) 
      mName = value 
     End Set 
    End Property 

End Class 
+0

vb.net 2015 dosen't work : ( – Rinos

1

를 대신 새 ListItem를 추가 Reader("Name")을 추가하는. ListItem에는 사용자가 설정할 수있는 TextValue 속성이 있습니다.

+0

당신은 목록 상자를 의미? 미안해, 이해 못해, 간단한 예를 보여 주실 수 있겠 니? –

14

. Klaus가 올바르다 고해도 ListItem 클래스는 System.Web.UI.WebControls 네임 스페이스의 멤버라고 생각합니다. 따라서 Windows Forms 솔루션에서 사용해서는 안됩니다. 그러나 그 자리에서 사용할 수있는 자신 만의 클래스를 만들 수 있습니다. 이 같은 MyListItem (또는 어떤 이름 선택)라는 간단한 클래스 만들기 : 당신이 당신의 콤보 상자에 항목을 추가 할 때 이제

Public Class MyListItem 
    Private mText As String 
    Private mValue As String 

    Public Sub New(ByVal pText As String, ByVal pValue As String) 
     mText = pText 
     mValue = pValue 
    End Sub 

    Public ReadOnly Property Text() As String 
     Get 
      Return mText 
     End Get 
    End Property 

    Public ReadOnly Property Value() As String 
     Get 
      Return mValue 
     End Get 
    End Property 

    Public Overrides Function ToString() As String 
     Return mText 
    End Function 
End Class 

을 당신은 이런 식으로 작업을 수행 할 수 있습니다

myComboBox.Items.Add(New MyListItem("Text to be displayed", "value of the item")) 

지금 당신이 당신의 콤보 상자에서 선택한 항목의 값을 검색 할 때 이런 식으로 작업을 수행 할 수 있습니다

Dim oItem As MyListItem = CType(myComboBox.SelectedItem, MyListItem) 
MessageBox.Show("The Value of the Item selected is: " & oItem.Value) 

여기 열쇠 중 하나는의 ToString 메서드를 오버라이드 (override)한다 수업. ComboBox가 표시되는 텍스트를 가져 오는 곳입니다.


매트이 더욱 유연하게하기 위해 제네릭 사용에 대한 아래 자신의 의견에, 우수한 강조했다. 그래서 나는 그것이 어떻게 생겼는지 궁금해했다.

다음은 새롭게 개선 된 GenericListItem 클래스의 :

Public Class GenericListItem(Of T) 
    Private mText As String 
    Private mValue As T 

    Public Sub New(ByVal pText As String, ByVal pValue As T) 
     mText = pText 
     mValue = pValue 
    End Sub 

    Public ReadOnly Property Text() As String 
     Get 
      Return mText 
     End Get 
    End Property 

    Public ReadOnly Property Value() As T 
     Get 
      Return mValue 
     End Get 
    End Property 

    Public Overrides Function ToString() As String 
     Return mText 
    End Function 
End Class 

그리고 여기 당신은 지금 당신의 콤보 상자에 일반 항목을 추가하는 방법입니다. 지금

Me.myComboBox.Items.Add(New GenericListItem(Of Integer)("Text to be displayed", 1)) 

그리고 항목의 검색 :이 경우 정수

Dim oItem As GenericListItem(Of Integer) = CType(Me.myComboBox.SelectedItem, GenericListItem(Of Integer)) 
MessageBox.Show("The value of the Item selected is: " & oItem.Value.ToString()) 

이 유형 Integer 객체 또는 값 유형의 모든 유형이 될 수 있음을 유의하십시오. 사용자 정의 클래스 중 하나의 객체가되고 싶다면 괜찮습니다.기본적으로이 접근 방식은 무엇이든합니다.

+0

+1 큰 대답 : -'mValue'를'String' 대신에'T'의 Generic Type''으로 만들면 "Enum", "Integer '등 여러분의 값을 –

10

이 질문은 5 세이지만 좋은 솔루션을 발견했습니다.

'DictionaryEntry'개체를 사용하여 키와 값을 쌍으로 만듭니다.

Me.myComboBox.DisplayMember = "Key" 
    Me.myComboBox.ValueMember = "Value" 

하면 콤보 상자에 항목을 추가하려면 :

Me.myComboBox.Items.Add(New DictionaryEntry("Text to be displayed", 1)) 

은 다음과 같이 항목을 retreive하려면

MsgBox(Me.myComboBox.SelectedItem.Key & " " & Me.myComboBox.SelectedItem.Value) 
+0

매우 멋지고, 매우 간단합니다. 답변을 계속 검색해 주어야합니다. –

+0

아주 좋은데, 이제는 키만있는 경우 어떻게 생각합니까? –

+0

다음을 사용하여 항목을 반복합니다. For ... 각 루프. Item.Key를 확인하십시오. http://stackoverflow.com/questions/32100580/find-if-value-contains-a-string-in-a-drop-down-list-in- vb-net –

0

는 'DisplayMember'과에 'ValueMember'속성을 설정합니다 예, 대부분의 경우 getter 및 setter를 사용하여 클래스를 만들 필요가 없습니다. 새 사전을 만들어 데이터 소스에 바인딩하면됩니다. 당신이 호출하여 필요한 어떤 값에 따라 또는

 Dim comboSource As New Dictionary(Of String, String)() 
     cboMenu.Items.Clear() 
     For I = 0 To SomeList.GetUpperBound(0) 
      comboSource.Add(SomeList(I).Prop1, SomeList(I).Prop2) 
     Next I 
     cboMenu.DataSource = New BindingSource(comboSource, Nothing) 
     cboMenu.DisplayMember = "Value" 
     cboMenu.ValueMember = "Key" 

는 그런 다음 데이터 그리드 뷰의 행을 설정할 수 있습니다 : 다음 목록에서 콤보 상자의 DisplayMember 및 ValueMember를 설정하는 for 루프를 사용하여 VB의 예입니다 클릭의 방법

Private Sub cboMenu_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cboMenu.SelectionChangeCommitted 
    SetListGrid(cboManufMenu.SelectedValue) 
End Sub 
0

이제 insert 방법을 사용할 수 있습니다 대신 add

' Visual Basic 
CheckedListBox1.Items.Insert(0, "Copenhagen") 
관련 문제