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

 

posted @   天天代码码天天  阅读(5)  评论(0编辑  收藏  举报  
编辑推荐:
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
点击右上角即可分享
微信分享提示