콤보박스에 바인딩 하기(딕셔너리 같은 것도 됨)
cbStatus.DataSource = dt;
cbStatus.ValueMember = "CODE";
cbStatus.DisplayMember = "CODE_NAME";
// Bind combobox to dictionary
Dictionary<string, string> test = new Dictionary<string, string>();
test.Add("1", "dfdfdf");
test.Add("2", "dfdfdf");
test.Add("3", "dfdfdf");
comboBox1.DataSource = new BindingSource(test, null);
comboBox1.DisplayMember = "Value";
comboBox1.ValueMember = "Key";
// Get combobox selection (in handler)
string value = comboBox1.SelectedValue.ToString();
string value = ((KeyValuePair<string, string>)comboBox1.SelectedItem).Value;
콤보박스에서 값과 텍스트를 분리하여 사용하기
public class ComboboxItem
{
public string Text { get; set; }
public object Value { get; set; }
public override string ToString()
{
return Text;
}
}
값 넣을 때
ComboboxItem c = new ComboboxItem();
c.Value = r["CODE"].ToString();
c.Text = r["CODE_NAME"].ToString();
cbStatus.Items.Add(c);
값 뺄 때
(cbStatus.SelectedItem as ComboboxItem).Value.ToString();
콤보박스에서 값을 임의로 변경못하게 하면서 리스트 색상은 그대로 유지하기
- 콤보박스의 높이를 조절할 때도 DrawMode를 OwnerDrawFixed 로 설정하고 DrawItem 이벤트를 설정해 주면 된다.
해당 콤보박스 설정에서 DrawMode = OwnerDrawFixed, DropDownStyle = DropDownList 로 변경
DrawItem 이벤트를 준 후 아래와 같이 코드 작성
private void cbStatus_DrawItem(object sender, DrawItemEventArgs e)
{
int index = e.Index >= 0 ? e.Index : 0;
var brush = Brushes.Black;
e.DrawBackground();
var ctrl = sender as ComboBox;
string itemText = string.Empty;
BindingSource bs;
if (ctrl.DataSource != null)
{
bs = (BindingSource)ctrl.DataSource;
if (e.Index > -1)
{
if (bs.DataSource is DataTable)
itemText = ((DataRowView)ctrl.Items[e.Index])[ctrl.DisplayMember].ToString();
else if (bs.DataSource is Dictionary<string, string> && ctrl.DisplayMember == "Key")
itemText = ((KeyValuePair<string, string>)ctrl.Items[e.Index]).Key.ToString();
else if (bs.DataSource is Dictionary<string, string> && ctrl.DisplayMember == "Value")
itemText = ((KeyValuePair<string, string>)ctrl.Items[e.Index]).Value.ToString();
}
}
else if (ctrl.Items.Count > 0)
itemText = ctrl.Items[index].ToString();
e.Graphics.DrawString(itemText, e.Font, brush, e.Bounds, StringFormat.GenericDefault);
e.DrawFocusRectangle();
}