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得到选中项




评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值