728x90

C# Dictionary 와 콤보박스 연결해서 값을 알아내는 걸 구글링하여 많은 예제를 보면서 경우 제대로 동작하는 걸 알게 되었다.

Dictionary 는 Hashtable 의 제네릭 버전이다.


콤보박스와 Binding 하는 소스는 쉽게 찾을 수 있다. 하지만 선택된 값이나 Key 값을 알아내는 걸 찾기가 쉽지 않았다.

comboBox1.SelectedItem 이 어떤 결과를 보여주는지는 코드를 직접 실행해보면서 확인하면 된다.


Dictionary <TKey, TValue> dic = new Dictionary <TKey, TValue>();

첫번째 아이템은 Key 이고, 두번째 아이템은 Value 이다.




using System;
using System.Collections.Generic;
using System.Windows.Forms;
 
namespace comboBox_Dictionary
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
 
        private void Form1_Load(object sender, EventArgs e)
        {
            selectedcomboBox();
        }
 
        private void selectedcomboBox()
        {
            var cBox = new Dictionary<stringint>();
            cBox.Add("일요일",1);
            cBox.Add("월요일",2);
            cBox.Add("화요일",3);
            cBox.Add("수요일",4);
            cBox.Add("목요일",5);
            cBox.Add("금요일",6);
            cBox.Add("토요일",7);
 
            comboBox1.DataSource = new BindingSource(cBox, null);
            comboBox1.DisplayMember = "Key";
            comboBox1.ValueMember = "Value";
            comboBox1.SelectedValue = 5;
        }
 
        private void button1_Click(object sender, EventArgs e)
        {
            KeyValuePair<stringint> selectedPair = (KeyValuePair<stringint>)comboBox1.SelectedItem;
            textBox1.Text = string.Format("Selected Text : {0} and Value : {1}", selectedPair.Key, selectedPair.Value);
 
            //textBox1.Text = string.Format("Selected Text:{0} and Value:{1}",comboBox1.SelectedItem,comboBox1.SelectedValue);
 
        }
    }
}

첨부파일에는 코드가 약간 더 있다.


comboBox_Dictionary.zip



개발자가 아닌지라 자주 사용하지 않아 오래되면 기억이 나질 않는다.

그래서 추가로 알게된 사항을 기록해둔다.

동일한 함수를 여러번 호출해서 사용해야 할 경우가 있다.
이때는
selectedcomboBox(comboBox1) 으로 처리한다.
private void selectedcomboBox(ComboBox CB)
{
    var cBox = new Dictionary<string, int>();
    cBox.Add("일요일", 1);
    cBox.Add("월요일", 2);
    cBox.Add("화요일", 3);
    cBox.Add("수요일", 4);
    cBox.Add("목요일", 5);
    cBox.Add("금요일", 6);
    cBox.Add("토요일", 7);

    CB.DataSource = new BindingSource(cBox, null);
    CB.DisplayMember = "Key";
    CB.ValueMember = "Value";
    CB.SelectedValue = 5; // 몇번째 항목을 default 로 선택할 것인가?
}

자동으로 변경되는 값을 DB에서 가져와서 뿌려줘야 한다면
void cat1comboBox(ComboBox CB)
{
    CB.Items.Clear();
    CB.Items.Add("전체");
    try
    {
        myConn = new MySqlConnection(GetConnectionString());
        myConn.Open();

        string strqry = "select uid, classname from category where relateduid=0";
        strqry += " order by uid";
        adapter = new MySqlDataAdapter(strqry, myConn);
        DataSet cat1 = new DataSet();
        adapter.Fill(cat1);

        foreach (DataRow dr in cat1.Tables[0].Rows)
        {
            CB.Items.Add(dr["classname"]);
        }
        CB.SelectedIndex = 0; // 첫번째 아이템 선택
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
    finally
    {
        this.myConn.Close();
    }
}

private void cat1comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
    cat2 = cat2comboBox(cat1comboBox1.SelectedItem.ToString(), cat2comboBox1); // 수정할 곳
    cat1name1 = cat1comboBox1.SelectedItem.ToString(); // TabPage1 의 cat1comboBox1

    myConn = new MySqlConnection(GetConnectionString());
    myConn.Open();

    string strqry = "select uid from category";
    strqry += " where relateduid=0 and classname='" + cat1name1 + "' "; // 수정할 곳

    MySqlCommand cmd = new MySqlCommand(strqry, myConn);
    cmd.CommandType = CommandType.Text;
    MySqlDataReader dr = cmd.ExecuteReader();
    while (dr.Read())
    {
        cat1uid1 = dr.GetString(0); // 수정할 곳
    }
    dr.Close();
    myConn.Close();
}


'C# > 문법 및 기능' 카테고리의 다른 글

자바와 C#의 차이점  (0) 2016.12.27
C# NameValueCollection  (0) 2016.03.20
C# Directory (폴더) 생성 및 삭제  (0) 2016.01.16
C# 시간 메소드  (0) 2016.01.15
C# 파일 입출력 개념 정리  (0) 2016.01.05
블로그 이미지

Link2Me

,