gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 15:43:57 26 4
gpt4 key购买 nike

我有一个 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com