2009-10-13 2 views
1

콤보 상자에서 "02"키를 사용하여 항목을 선택하려면 어떻게해야합니까?개체가로드 된 ComboBox에서 값 선택

public class GenericComboBox 
{ 
    private string _key = string.Empty; 
    private string _value = string.Empty; 

    public string Key 
    { 
     get { return _key; } 
     set { _key = value; } 
    } 

    public string Value 
    { 
     get { return _value; } 
     set { _value = value; } 
    } 

    public GenericComboBox(string key, string value) 
    { 
     _key = key; 
     _value = value; 
    } 
} 

//Add data 
IList<GenericComboBox> data = new List<GenericComboBox>(); 

data.Add(new GenericComboBox("01", "01 text")); 
data.Add(new GenericComboBox("02", "02 text")); 
data.Add(new GenericComboBox("03", "03 text")); 

comboBox1.DataSource = data; 
comboBox1.ValueMember = "Value"; 

//comboBox1.SelectItem With key equal "02" 

감사합니다.

답변

1

닷넷 2.0 : (데이터는이 일에 대한 목록이 아닌 IList의를 할 필요가있다.)

this.comboBox1.SelectedItem = data.Find(delegate(GenericComboBox gc) {return gc.Key == "02"; }); 

닷넷 3.5 :

this.comboBox1.SelectedItem = data.First(gc => gc.Key == "02"); 
+0

이 어떻게 변수 데이터에 대한 액세스 권한을 가지고 있지의 경우에 할 수있다? 예를 들어 버튼 클릭 이벤트에서 comboBox를 선택하는 경우 –

+0

comboBox1.SelectedItem = ((List ) comboBox1.DataSource) .Find (GenerateComboBox gc) {return gc.Key == "02";}) ; –

1

SelectedValue 속성을 설정하십시오. ComboBox은 해당 값이 설정된 항목을 선택합니다.

0

어떻게 IList의 대신 사전 사용에 대한? 그런 다음 키를 사용하여 값을 검색 할 수 있습니다. 당신의 GenericComboBox 클래스

1

재정 Equals :

public override bool Equals(object obj) 
{ 
    return string.Compare(Key, obj.ToString(), true) == 0; 
} 

다음이 코드가 작동해야합니다

comboBox1.SelectedItem = "02";