본문 바로가기

.NET/Winforms

[WINFORMS] ComboBox Control data bind

ComboBox Control

  • Drop down 형태의 기본 컨트롤
  • Design 영역에서 직접 데이터를 삽입하는 방법도 있으나 Dictionary 를 이용해  KEY - VALUE 형태로 관리하는 방법을 서술한다.

1. Dictionary 생성

Dictionary<int, string> dict = new Dictionary<int, string>
{
    { 1, "OK" },
    { 2, "NG" }
};

2. KeyValuePairs 객채로 변환

List<KeyValuePair<int, string>> listData = dict.ToList();

3. 데이터 바인딩

comboBox.DataSource = new BindingSource(listData, null);
comboBox.DisplayMember = "Value";  // Display the value (string) in the ComboBox
comboBox.ValueMember = "Key";      // Use the key (int) as the selected value

4. 함수 코드

        private void BindComboBox(ComboBox comboBox) {

            Dictionary<int, string> dict = new Dictionary<int, string>
            {
                { 1, "OK" },
                { 2, "NG" }
            };

            List<KeyValuePair<int, string>> listData = dict.ToList();

            comboBox.DataSource = new BindingSource(listData, null);
            comboBox.DisplayMember = "Value";  // Display the value (string) in the ComboBox
            comboBox.ValueMember = "Key";      // Use the key (int) as the selected value

            comboBox.SelectedIndex = -1;
        }

5. Change Event

private void comboBox_SelectedIndexChanged(object sender, EventArgs e)
{
    if (comboBox.SelectedValue != null)
    {
        int selectedKey = (int)comboBox.SelectedValue;
        string selectedValue = (string)comboBox.SelectedItem;
        // Do something with the selected key and value
    }
}

6. 일치하는 KEY 값 찾기

int indexToSelect = comboBox.FindString("OK");  // Find index based on the value
comboBox.SelectedIndex = indexToSelect;

There might be incorrect information or outdated content.