C#涓璫ombox鎬庝箞鏄剧ず鍊煎拰鍙傛暟
鍦–#涓娇鐢–omboBox鎺т欢鏄剧ず鍊煎拰鍙傛暟鏈夊嚑绉嶅父鐢ㄧ殑鏂规硶锛?/p>
- 浣跨敤鏁版嵁缁戝畾锛氬彲浠ラ€氳繃璁剧疆ComboBox鐨凞ataSource灞炴€ф潵缁戝畾鏁版嵁婧愶紝鐒跺悗璁剧疆DisplayMember鍜孷alueMember灞炴€ф潵鎸囧畾鏄剧ず鍊煎拰鍙傛暟锛屼緥濡傦細
// 鍋囪鏈変竴涓寘鍚€煎拰鍙傛暟鐨勬暟鎹簮
List<KeyValuePair<string, int>> data = new List<KeyValuePair<string, int>>
{
new KeyValuePair<string, int>("Value1", 1),
new KeyValuePair<string, int>("Value2", 2),
new KeyValuePair<string, int>("Value3", 3)
};
// 缁戝畾鏁版嵁婧?/span>
comboBox.DataSource = data;
// 璁剧疆鏄剧ず鍊煎拰鍙傛暟鐨勫瓧娈靛悕
comboBox.DisplayMember = "Key";
comboBox.ValueMember = "Value";
- 鎵嬪姩娣诲姞椤癸細鍙互閫氳繃Add鏂规硶鎵嬪姩娣诲姞姣忎釜椤癸紝骞堕€氳繃Tag灞炴€ц缃弬鏁帮紝渚嬪锛?/li>
comboBox.Items.Add(new KeyValuePair<string, int>("Value1", 1));
comboBox.Items.Add(new KeyValuePair<string, int>("Value2", 2));
comboBox.Items.Add(new KeyValuePair<string, int>("Value3", 3));
// 鑾峰彇閫変腑椤圭殑鍙傛暟鍊?/span>
int param = ((KeyValuePair<string, int>)comboBox.SelectedItem).Value;
- 浣跨敤鑷畾涔夌被锛氬彲浠ュ垱寤轰竴涓寘鍚€煎拰鍙傛暟鐨勮嚜瀹氫箟绫伙紝鐒跺悗璁剧疆ComboBox鐨凞ataSource灞炴€т负璇ョ被鐨勯泦鍚堬紝濡備笅鎵€绀猴細
public class CustomItem
{
public string DisplayValue { get; set; }
public int ParamValue { get; set; }
public override string ToString()
{
return DisplayValue;
}
}
// 鍒涘缓鑷畾涔夌被鐨勯泦鍚?/span>
List<CustomItem> items = new List<CustomItem>
{
new CustomItem { DisplayValue = "Value1", ParamValue = 1 },
new CustomItem { DisplayValue = "Value2", ParamValue = 2 },
new CustomItem { DisplayValue = "Value3", ParamValue = 3 }
};
// 缁戝畾鏁版嵁婧?/span>
comboBox.DataSource = items;
comboBox.DisplayMember = "DisplayValue";
comboBox.ValueMember = "ParamValue";
浠ヤ笂鏄嚑绉嶅父鐢ㄧ殑鏂规硶鏉ュ湪C#涓娇鐢–omboBox鎺т欢鏄剧ず鍊煎拰鍙傛暟锛屽彲浠ユ牴鎹叿浣撻渶姹傞€夋嫨鍚堥€傜殑鏂瑰紡鏉ュ疄鐜般€?/p>
相关问答