Ash*_*ish 2 dictionary listbox
我正在尝试将字典中的键/值对显示到ListBox.
Key Value
A 10
B 20
C 30
Run Code Online (Sandbox Code Playgroud)
我想以下列格式在ListBox中显示它们
A(10)
B(20)
C(30)
Run Code Online (Sandbox Code Playgroud)
使用以下代码我已经能够将Listbox.Datasource链接到Dictionary.
myListBox.DataSource = new BindingSource(myDictionary, null);
Run Code Online (Sandbox Code Playgroud)
它显示为
[A, 10]
[B, 20]
[C, 30]
Run Code Online (Sandbox Code Playgroud)
我无法弄清楚如何格式化它,以便以我想要的方式显示它.
任何帮助将不胜感激.
谢谢Ashish
使用列表框上的格式事件:
KeyValuePair<string, int> item = (KeyValuePair<string, int>)e.ListItem;
e.Value = string.Format("{0}({1})", item.Key, item.Value);
Run Code Online (Sandbox Code Playgroud)
为了获得适当的长期灵活性,我会尝试使用一个类型化的对象,然后你可以做你以后喜欢的事情,引发事件,更改值,不必使用唯一键,从列表框中获取真实对象而不仅仅是格式化字符串
public partial class tester : Form
{
public tester()
{
InitializeComponent();
List<MyObject> myObjects = new List<MyObject>();
MyObject testObject = new MyObject("A", "10");
myObjects.Add(testObject);
BindingSource bindingSource = new BindingSource(myObjects,null);
listBox1.DisplayMember = "DisplayValue";
listBox1.DataSource = bindingSource;
}
}
public class MyObject
{
private string _key;
private string _value;
public MyObject(string value, string key)
{
_value = value;
_key = key;
}
public string Key
{
get { return _key; }
}
public string Value
{
get { return _value; }
}
public string DisplayValue
{
get { return string.Format("{0} ({1})", _key, _value); }
}
}
Run Code Online (Sandbox Code Playgroud)