반응형
    
    
    
  다음 코드는 콤보박스에 딕셔너리 데이터를 넣고, 키와 값을 사용하는 예제를 보인것입니다.
using System;
using System.Collections.Generic;
using System.Windows.Forms;
namespace WindowsFormsApp1
{
    public partial class Form1 : Form
    {
        Dictionary<string, string> dic = new Dictionary<string, string>();
        public Form1()
        {
            InitializeComponent();
        }
        private void Form1_Load(object sender, EventArgs e)
        {
            dic.Add("01", "기계공학과");
            dic.Add("02", "전자공학과");
            dic.Add("12", "컴퓨터공학과");
            comboBox1.DataSource = new BindingSource(dic, null);
            comboBox1.DisplayMember = "Value";
            comboBox1.ValueMember = "Key";
            comboBox1.SelectedIndex = 0;
        }
        private void button1_Click(object sender, EventArgs e)
        {
            //KeyValuePair<string, string> selected =
            //    (KeyValuePair<string, string>)comboBox1.SelectedItem;
            //label1.Text = selected.Key;
            //label2.Text = selected.Value;
            label1.Text = comboBox1.SelectedValue.ToString();  // 01
        }
        private void button2_Click(object sender, EventArgs e)
        {
            string key = "12";
            comboBox1.Text = dic[key];
        }
    }
}
'C#' 카테고리의 다른 글
| C#, 윈폼(WinForms)과 WPF 프로그램의 차이 (0) | 2025.01.28 | 
|---|---|
| 데이터베이스 연결 문자열 모음 Database connection string (1) | 2024.10.30 | 
| C#, using 키워드의 3가지 용도 (0) | 2024.10.13 | 
| C#, 텍스트 파일 읽기 저장 StreamReader StreamWriter File.WriteAllText File.WriteAllLines ReadLine (0) | 2024.10.12 | 
| (C#) 폼 이벤트: Form_Load, FormClosing, FormClosed, 폼 닫기 (0) | 2024.05.14 |