C#
C#, 콤보박스 딕셔너리 키 값 사용하기 comboBox dictionary key value
코딩ABC
2024. 11. 21. 13:50
반응형
다음 코드는 콤보박스에 딕셔너리 데이터를 넣고, 키와 값을 사용하는 예제를 보인것입니다.
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];
}
}
}
반응형