Skip to content

Instantly share code, notes, and snippets.

@relyky
Last active August 29, 2015 14:23
Show Gist options
  • Save relyky/3ba75220e006b75ea45c to your computer and use it in GitHub Desktop.
Save relyky/3ba75220e006b75ea45c to your computer and use it in GitHub Desktop.
ComboBox初始化
// 有三種方式使用ComboBox
// 直接看例子比較快
// 法一:純文字
cbxAuthLevel.Items.Add("選項一");
cbxAuthLevel.Items.Add("選項二");
cbxAuthLevel.Items.Add("選項三");
cbxAuthLevel.Text //<-- 操作時,使用此屬性
// 法二:用Items屬性初始化,搭配KeyValuePair。
//# init. : cbxAuthLevel
foreach (AuthenticationLevel c in Enum.GetValues(typeof(AuthenticationLevel)))
cbxAuthLevel.Items.Add(new KeyValuePair<AuthenticationLevel, string>(c, c.ToString()));
cbxAuthLevel.ValueMember = "Key"; //<-- 記得要指定 Key, Value
cbxAuthLevel.DisplayMember = "Value";
cbxAuthLevel.SelectedIndex = 0;
cbxAuthLevel.SelectedItem //<-- 操作時,使用此屬性
// 法三:用DataSource屬性初始化,搭配 ArrayList、KeyValuePair。
//# init. : cbxAuthLevel
ArrayList authLevelItems = new ArrayList();
foreach (AuthenticationLevel c in Enum.GetValues(typeof(AuthenticationLevel)))
authLevelItems.Add(new KeyValuePair<AuthenticationLevel, string>(c, c.ToString()));
cbxAuthLevel.ValueMember = "Key";
cbxAuthLevel.DisplayMember = "Value";
cbxAuthLevel.DataSource = authLevelItems; // 好處是 Data Source 可共用。
cbxAuthLevel.SelectedValue //<-- 操作時,使用此屬性
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment