public class ComboboxItem { public string Text { get; set; } public object Value { get; set; } public override string ToString() { return Text; } } private void Test() { ComboboxItem item = new ComboboxItem(); item.Text = "Item text1"; item.Value = 12; comboBox1.Items.Add(item); comboBox1.SelectedIndex = 0; MessageBox.Show((comboBox1.SelectedItem as ComboboxItem).Value.ToString()); }
* Add 2 : DataBase 연동
private void frmCityMapping_Load(object sender, EventArgs e) { string ConnectionString = "server=아이피;database=데이터베이스;uid=아이디;pwd=패스워드;"; try { SqlConnection dbConn = new SqlConnection(ConnectionString); dbConn.Open(); SqlCommand cmd = new SqlCommand("SELECT splyCd,splyEnm FROM tblsupply order by splyEnm", dbConn); using(var myReader = cmd.ExecuteReader()) { while (myReader.Read()) { splyCd.Items.Add(new comboboxItem(myReader["splyEnm"].ToString(), myReader["splyCd"].ToString())); } splyCd.SelectedIndex = 0; } cmd.CommandText = "SELECT nationCd,nationENm FROM tblNation order by nationENm"; using(var myReader = cmd.ExecuteReader()) { while (myReader.Read()) { nationCd.Items.Add(new comboboxItem(myReader["nationENm"].ToString(), myReader["nationCd"].ToString())); } nationCd.SelectedIndex = 0; } dbConn.Dispose(); dbConn.Close(); } catch (Exception b) { MessageBox.Show(b.ToString()); } } public class comboboxItem { public string Text { get; set; } public object Value { get; set; } public override string ToString() { return Text; } public comboboxItem(string text, object value) { Text = text; Value = value; } }
* Set : 값 지정하기
nationCd.Text = "KR";
* Get : 선택 값 가져오기
comboboxItem item; item = (comboboxItem)nationCd.SelectedItem; string nationValue = item.Value.ToString();