天天看點

WinForm中ComboBox添加Key/Value項、擷取選中項、根據Key、Value設定選中項總結

轉載請保留出處:http://blog.csdn.net/tp7309/article/details/9077287

WinForm下的ComboBox預設是以多行文本來設定顯示清單的, 這通常不符合大家日常的應用, 

因為大家日常應用通常是鍵/值對的形式去綁定它的.

參考了一些網上的例子,最終寫了一個輔助類用于友善對ComboBox的操作:

用下面這個類的執行個體作為ComboBox的添加項:

using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;

namespace tp7309.Winform
{
    public class ListItem
    {
        public string Key { get; set; }
        public string Value { get; set; }

        public ListItem(string strKey, string strValue)
        {
            this.Key = strKey;
            this.Value = strValue;
        }
        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)
        {
            return cmb.Items.Cast<MyListItem>().FirstOrDefault(li => li.Value == strValue);
        }

        /// <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 FindByText(ComboBox cmb, string strText)
        {
            return cmb.Items.Cast<MyListItem>().FirstOrDefault(li => li.Value == strText);
        }
    }
}
           

使用前引入命名空間:tp7309.Winform

添加項:

cmb1.Items.Add(new ListItem("key1", "value1"));
cmb1.Items.Add(new ListItem("key2", "value2"));
           

擷取選中項:

ListItem li = (ListItem)cmb1.SelectedItem;
ListItem li1 = ListItem.FindByValue(cmb1, "value1");   //根據Key得到選中項
ListItem li2 = ListItem.FindByText(cmb1, "key1");      //根據Value得到選中項
string strKey = li.Key;   //得到選中項Key
string strValue = li.Value;   //得到選中項Value
           

設定選中項:

cmb1.SelectedIndex = 0;    //根據索引修改選中項
cmb1.SelectedItem = ListItem.FindByValue(cmb1, "value1");   //根據Key得到選中項
cmb1.SelectedItem = ListItem.FindByText(cmb1, "key1");      //根據Value得到選中項
           

繼續閱讀