2017-01-30 12 views
2

콤보 박스의 이름과 값 쌍을 설정하고 싶습니다.C# Winforms - 콤보 박스 선택 값 설정

// Content item for the combo box 
private class Item 
{ 
    private readonly string Name; 
    private readonly int Value; 
    private Item(string _name, int _value) 
    { 
     Name = _name; Value = _value; 
    } 
    private override string ToString() 
    { 
     // Generates the text shown in the combo box 
     return Name; 
    } 
} 

그리고 데이터 것은 다음과 같이 설정합니다 : 내 예에서

// 1 - Europe 
// 2 - Asia 
// 3 - Africa 
// 4 - North America 
// 5 - South America 
// 6 - Australia 
// 7 - Antartica 

아프리카 대륙이 있어야합니다 : 여기

comboBox1.DataSource = null; 
comboBox1.Items.Clear(); 
// For example get from database continentals. 
var gets = _connection.Continentals; 
comboBox1.Items.Add(new Item("--- Select a continental. ---", 0)); 
foreach (var get in gets) 
{ 
    comboBox1.Items.Add(new Item(get.name.Length > 40 ? get.name.Substring(0, 37) + "..." : get.name, Convert.ToInt32(get.id))); 
} 
// It points Africa. 
comboBox1.SelectedValue = 3; 

는 출력 그래서 나는이 같은 Item라는 이름의 클래스를 생성 선택되었지만 그렇지 않습니다.

var a = _connection.persons.SingleOrDefault(x => x.id == Id);

가 나는 코드 comboBox2.SelectedValue = a.continental, 아프리카 대륙을 선택해야 할 때,하지만되지 않습니다 :보다 그리고 더 내 편집 형태, 예를 들어,이 코드는 person 테이블에서 datas를 가져옵니다. 나는 그 문제를 해결하지 못했다. SelectedValue 등록 문서에 설명

+0

나는 SelectedIndex = 3 또는 SelectedIndex = IndexOf()가 필요하다고 생각한다. –

+1

SelectedItem, ComboBox에서 현재 선택된 항목을 가져 오거나 설정합니다. – bashkan

답변

4

로서 :

속성 값
ValueMember 속성에 의해 지정된 데이터 소스의 멤버의 값을 포함하는 객체.

는 속성이 ValueMember에 지정되지 않은 경우, SelectedValue가 개체의 ToString 방법의 결과를 반환
비고.

// Content item for the combo box 
private class Item 
{ 
    public string Name { get; private set; } 
    public int Value { get; private set; } 
    private Item(string _name, int _value) 
    { 
     Name = _name; Value = _value; 
    } 
} 

및 샘플 사용 :

가 원하는 동작을 얻으려면, 당신은 당신의 Item 클래스의 공용 속성으로 NameValue을 노출하고 컨트롤의 DataSource, ValueMemberDisplayMember 특성을 활용해야 :

// Build a list with items 
var items = new List<Item>(); 
// For example get from database continentals. 
var gets = _connection.Continentals; 
items.Add(new Item("--- Select a continental. ---", 0)); 
foreach (var get in gets) 
{ 
    items.Add(new Item(get.name.Length > 40 ? get.name.Substring(0, 37) + "..." : get.name, Convert.ToInt32(get.id))); 
} 
// Bind combobox list to the items 
comboBox1.DisplayMember = "Name"; // will display Name property 
comboBox1.ValueMember = "Value"; // will select Value property 
comboBox1.DataSource = item; // assign list (will populate comboBox1.Items) 

// Will select Africa 
comboBox1.SelectedValue = 3; 
+1

알다시피,이 텍스트 상자는 더 많은 정보를 요구하기위한 것이지만 도움을 주셔서 대단히 감사합니다. –