随笔 - 252, 文章 - 13, 评论 - 176, 阅读 - 58万
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

 

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)
        {
            foreach (ListItem li in cmb.Items)
            {
                if (li.Value == 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 FindByText(ComboBox cmb, string strText)
        {
            foreach (ListItem li in cmb.Items)
            {
                if (li.Value == strText)
                {
                    return li;
                }
            }
            return null;
        }
    }
}
复制代码

 

 

使用前引入命名空间: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得到选中项

编辑推荐:
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!
点击右上角即可分享
微信分享提示