c# - 在 Combobox 中使用字典作为 ValueMember

标签 c# .net winforms combobox

我有一个 combobox ,我想在这里显示一个字符串作为 DisplayMember并且有一个Dictionary<string,string>作为ValueMember .我有一个包含带有字符串和字典的对象的列表,这个列表我用作 DataSource对于 ComboBox .

List<myObject> myList = new List<myObject>{
 new myObject {myDisplayMember = "TEXT", myValueMember = new Dictionary<string,string> {{"A","ABC"},{"D","DEF"}}}
};

myComboBox.DataSource = new BindingSource(myList, null);
myComboBox.DisplayMember = "myDisplayMember";
myComboBox.ValueMember = "myValueMember";

DisplayMember按预期工作,“TEXT”显示在 ComboBox 中,但是当我得到 ValueMember我只得到一串“myValueMember”,而不是我想得到的字典。我正在尝试的方法是否可行,或者是否有更好的选择?

最佳答案

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load( object sender, EventArgs e )
        {
            var list = new List<ItemX>() { 
                new ItemX { Name = "a", Dictionary = new Dictionary<string, string> { { "1", "2" },{"qqq","wwww"} } },
                new ItemX { Name = "b", Dictionary = new Dictionary<string, string> { { "3", "4" } } },
                new ItemX { Name = "c", Dictionary = new Dictionary<string, string> { { "5", "6" } } },
            };

            comboBox1.DataSource = list;
            comboBox1.DisplayMember = "Name";
            comboBox1.ValueMember = "Dictionary";
        }

        private void button1_Click( object sender, EventArgs e )
        {
            if ( comboBox1.SelectedValue != null )
            {
                var d = comboBox1.SelectedValue as Dictionary<string, string>;

                if ( d != null )
                {
                    var builder = new StringBuilder();

                    foreach ( KeyValuePair<string, string> p in d )
                    {
                        builder.AppendFormat( "key:{0} value:{1}\n", p.Key, p.Value );
                    }

                    MessageBox.Show( builder.ToString() );
                }
            }
        }
    }

    public class ItemX
    {
        public string Name { get; set; }
        public Dictionary<string, string> Dictionary { get; set; }
    }
}

关于c# - 在 Combobox 中使用字典作为 ValueMember,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28991519/

相关文章:

c# - 为什么我不能使用 interop outlook 检索所有 MailItems?

c# - 创建下拉列表

c# - 如何使用户能够从 ASP.NET MVC 发送电子邮件?

C# EMIT IL 性能问题

.Net 单元测试编译错误 - 类型或方法有 2 个通用参数,但提供了 1 个通用参数

c# - 防止在 C# TextBox 中打印空格

c# - Listview 选中的项目颜色变为灰色

c# - 从 xml 向数据库中插入记录

c# - 自定义错误消息不出现数据注释

c# - 获取 Windows 中某个键的 'Shift' 表示