2011-12-01 3 views
1

콤보 상자 구성 요소가 있는데 comboBox1.Items.Add("Item1")과 같은 항목을 추가하고 있습니다. 그러나 나는이 아이템에 관한 다른 정보를 알 필요가있다. 그래서 "Item1"을 클릭하면 "102454"이 필요합니다. 102454를 콤보 상자의 "Item1"에 저장할 수 있습니까?웹 응용 프로그램의 드롭 다운 목록과 같은 C# 콤보 상자

웹 aplication에서

<select> 
    <option value="102454">Item1</option> 
</select> 

처럼 내가 "항목 1"을 클릭하면 내가 102454를 얻을 수 드롭 다운 목록이 있습니다.

콤보 상자가있는 Windows 데스크톱 응용 프로그램에서이 작업을 수행 할 수 있습니까?

답변

3

편집 더 나은 솔루션 :

사용 KeyValuePairValueMemberDisplayValue \ A : 크리스티앙이 지적 하듯이

comboBox1.ValueMember = "Key"; 
comboBox1.DisplayMember = "Value"; 

comboBox1.Items.Add(new KeyValuePair<int, string>(102454, "Item1")); 

이 더욱 유연하게 확장 할 수 있습니다 - 당신은 당신이 원하는대로 개체를 넣을 수 있습니다 항목 목록에 추가하고 콤보 상자의 값과 표시 멤버를 원하는 속성 경로로 설정합니다.


나중에 당신이 할 수있는 다시 키를 얻으려면 :

var item = combobox1.SelectedItem; 

int key = ((KeyValuePair<int, string>)item).Key; 
+1

이 가장 유연한 솔루션입니다 :

public class ListItem<TKey> : IComparable<ListItem<TKey>> { /// <summary> /// Gets or sets the data that is associated with this ListItem instance. /// </summary> public TKey Key { get; set; } /// <summary> /// Gets or sets the description that must be shown for this ListItem. /// </summary> public string Description { get; set; } /// <summary> /// Initializes a new instance of the ListItem class /// </summary> /// <param name="key"></param> /// <param name="description"></param> public ListItem(TKey key, string description) { this.Key = key; this.Description = description; } public int CompareTo(ListItem<TKey> other) { return Comparer<String>.Default.Compare (Description, other.Description); } public override string ToString() { return this.Description; } } 

그것의 제네릭이 아닌 변형을 생성하는 것이 용이하다. "KeyValuePair"는 모든 객체로 변경할 수 있습니다. 예를 들어 "Person"개체로 설정할 수 있습니다. comboBox1.ValueMember = "SSN"; comboBox1.DisplayMember = "Name"; – ravndal

+0

xx 시도 할 것입니다. 하지만 올바른 코드는 KeyValuePair (102454, "Item1") – senzacionale

+0

흠 어떻게 키를 다시 얻을 수 있습니까? 102454를 읽지 못하거나 내가 할 수 있습니까? – senzacionale

0

마크 핌 (Mark Pim)과 비슷한 클래스를 만들었습니다. 그러나 제 산은 제네릭을 사용합니다. Value 속성을 문자열 유형으로 지정하지는 않을 것입니다.

public class ListItem : ListItem<object> 
    { 
     /// <summary> 
     /// Initializes a new instance of the <see cref="ListItem"/> class. 
     /// </summary> 
     /// <param name="key"></param> 
     /// <param name="description"></param> 
     public ListItem(object key, string description) 
      : base (key, description) 
     { 
     } 
    } 
관련 문제