C#(winform)自定义ListItem类方便ComboBox操作
public class ListItem
{
/// <summary>
/// Key
/// </summary>
public string Key { get; set; }
/// <summary>
/// Value
/// </summary>
public object Value { get; set; }
/// <summary>
/// 构造函数
/// </summary>
public ListItem(string strKey, string strValue)
{
this.Key = strKey;
this.Value = strValue;
}
/// <summary>
/// 重写的ToString
/// </summary>
public override string ToString()
{
return this.Key;
}
/// <summary>
/// 根据ListItem中的Value找到特定的ListItem(ComboBox的Item设置为ListItem时有效)
/// </summary>
/// <param name="cmb">要查找的ComboBox</param>
/// <param name="strValue">要查找ListItem的Value</param>
/// <returns>返回ComboBox中符合条件的第一个ListItem,否则返回null</returns>
public static ListItem FindByValue(ComboBox cmb, string strValue)
{
foreach (ListItem li in cmb.Items)
{
if (li.Value.ToString() == strValue)
{
return li;
}
}
return null;
}
/// <summary>
/// 根据ListItem中的Key找到特定的ListItem(ComboBox的Item设置为ListItem时有效)
/// </summary>
/// <param name="cmb">要查找的ComboBox</param>
/// <param name="strValue">要查找ListItem的Key</param>
/// <returns>返回ComboBox中符合条件的第一个ListItem,否则返回null</returns>
public static ListItem FindByKey(ComboBox cmb, string strText)
{
foreach (ListItem li in cmb.Items)
{
if (li.Key == strText)
{
return li;
}
}
return null;
}
}
//添加项:
cmbTest.Items.Add(new ListItem("key1", "value1"));
cmbTest.Items.Add(new ListItem("key2", "value2"));
//设置选中项:
cmbTest.SelectedIndex = 0; //根据索引
cmbTest.SelectedItem = ListItem.FindByValue(cmbTest, "value1"); //根据Key获取并设置选中项
cmbTest.SelectedItem = ListItem.FindByText(cmbTest, "key1"); //根据Value获取并设置选中项
//获取选中项:
ListItem li = (ListItem)cmbTest.SelectedItem;
ListItem li1 = ListItem.FindByValue(cmbTest, "value1"); //根据Key获取并设置选中项
ListItem li2 = ListItem.FindByText(cmbTest, "key1"); //根据Value获取并设置选中项
string strKey = li.Key; //获取选中项Key
string strValue = li.Value; //获取选中项Value