1. 程式人生 > >c#(winform)中自定義ListItem類方便ComboBox添加Item項

c#(winform)中自定義ListItem類方便ComboBox添加Item項

urn left over string his 定義 return box item

1.定義ListItem類

public class ListItem

{

private string _key = string.Empty;

private string _value = string.Empty;

public ListItem(string pKey, string pValue)

{

_key = pKey;

_value = pValue;

}

public override string ToString()

{

return this._value;

}

public string Key

{

get

{

return this._key;

}

set

{

this._key = value;

}

}

public string Value

{

get

{

return this._value;

}

set

{

this._value = value;

}

}

}


2.使用

ListItem listItem1 = new ListItem("1","中國");

ListItem listItem2 = new ListItem("1","美國");

ListItem listItem3 = new ListItem("1","英國");

comboBox1.Items.Add(listItem1);

comboBox1.Items.Add(listItem2);

comboBox1.Items.Add(listItem3);


3.取值

string id = ((ListItem)comboBox1.SelectedItem).Key;

string value = ((ListItem)comboBox1.SelectedItem).Value;



4.默認選中項
comboBox1.SelectedIndex = 0;//設置第一項為默認選擇項
comboBox1.SelectedItem = listItem1//設置指定的項為默認選擇項

c#(winform)中自定義ListItem類方便ComboBox添加Item項