【问题标题】:Using a Dictionary as ValueMember in Combobox在 Combobox 中使用字典作为 ValueMember
【发布时间】:2015-05-13 12:45:55
【问题描述】:

我有一个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”,而不是我想要的字典要得到。我正在尝试的方法是否可行,还是有更好的选择?

【问题讨论】:

  • 您是如何尝试获取 value 成员的?你能显示代码吗?你在看SelectedValue 财产还是什么?那应该行得通。如果您查看ValueMember 属性,显然它将是您指定的字符串。
  • 嗯,这是一个愚蠢的问题。 @SriramSakthivel,你是对的。我没有看 SelectedValue。
  • 哈哈哈,嗯,发生了:)

标签: c# .net winforms combobox


【解决方案1】:
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; }
    }
}

【讨论】:

    猜你喜欢
    • 2017-11-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多