WinForms C# ComboBox 設定值的幾種方式
範例說明下列情況:
如何在 combobox 賦予 items 預設值, 如何從DB取值再加入combobox items 如何設定 combobox key value 值
public MYFORMS()
{
InitializeComponent();
MSSqlHelper.Initialize(); //初始化資料庫連線設定
initCombobox();
}
private void initCombobox()
{
//Order Buy Sell Kind
cbdata = new Dictionary<string, string>();
cbdata.Clear();
cbdata.Add("1", "Yes");
cbdata.Add("2", "No");
DBELEM2.DataSource = new BindingSource(cbdata, null);
DBELEM2.DisplayMember = "Value";
DBELEM2.ValueMember = "Key";
DBELEM2.SelectedIndex = -1;
}
private void MYFORMS_Load(object sender, EventArgs e)
{
setCB();
}
private void setCB()
{
dt = MSSqlHelper.GetDataTable("SELECT COMNAME FROM TABLENAME WHERE ID = 'A'", null);
if (dt != null)
{
for (int i = 0; i < dt.Rows.Count; i++)
{
ComboboxItem item = new ComboboxItem();
item.Text = "Name: "+dt.Rows[i]["COMNAME"].ToString();
item.Value = dt.Rows[i]["COMNAME"].ToString();
CBELEM.Items.Add(item);
}
}
}//.setCB
public class ComboboxItem
{
public string Text { get; set; }
public object Value { get; set; }
public override string ToString()
{
return Text;
}
}
取得 COMBOBOX Key 值方式
如果使用 Text 只會取得 Value 屬性,可以透過 SelectedValue 取得 Key
若要在 ComboBox SelectedIndexChanged 的時候,判斷key執行動作時
記得要先在一開始寫入 if (COMBOBOX.SelectedValue == null){ return }
範例:
if (COMBOBOX.SelectedValue == null)
{
return;
}
string buy_sell_value = COMBOBOX.SelectedValue.ToString();
label11.Text = buy_sell_value;
switch (buy_sell_value)
{
case "S":
COMBOBOX.BackColor = Color.Red;
break;
case "B":
COMBOBOX.BackColor = Color.Blue;
break;
default:
COMBOBOX.BackColor = Color.White;
break;
}