플밍

Combobox 를 Key & Value (Text or Value) 로 사용하기 본문

프로그래밍/C#

Combobox 를 Key & Value (Text or Value) 로 사용하기

너구리안주 2020. 4. 15. 14:15

c# 의 combobox 컨트롤은 하나의 객체만 추가할 수 있다.

그래서 html 의 <select> 처럼 보이는 값(Text) 따로 실제 값(Value) 따로 세팅해서 사용하기가 번거롭다.

여러가지 방법이 있지만 경험상 가장 간단한 방법을 소개한다.

바로 object 와 BindingList 를 사용하는 방법이다.

아래 예제를 참고하면 아주 간단하게 적용할 수 있다.

public partial class Form1: Form
{
    private BindingList<object> typeList = new BindingList<object>();
 
    public Form()
    {
        typeList.Add(new { Text = "부모님", Value = "parents" });
        typeList.Add(new { Text = "선생님", Value = "teacher" });
        typeList.Add(new { Text = "학생", Value = "student" });
 
        combobox1.DataSource = typeList;
        combobox1.DisplayMember = "Text";
        combobox1.ValueMember = "Value";
 
        button1.Click += button1_Click;
    }
 
    private void button1_Click(object sender, EventArgs e)
    {
        string typeValue = combobox1.SelectValue.ToString();
        MessageBox.Show(typeValue);  // Value 에 해당하는 parents or teacher or student 가 출력된다
    }
}

 

Comments