如何在列表框中显示字典

问题描述 投票:0回答:4

我正在尝试将字典中的键/值对显示到列表框。

Key Value
A    10
B    20
C    30

我想以以下格式将它们显示在列表框中

A(10)
B(20)
C(30)

使用以下代码我已经能够将 Listbox.Datasource 链接到 Dictionary。

myListBox.DataSource = new BindingSource(myDictionary, null);

其显示为

[A, 10]
[B, 20]
[C, 30]

我不知道如何格式化它,以便它以我想要的方式显示。

任何帮助将不胜感激。

谢谢 阿什什

dictionary listbox
4个回答
8
投票

使用列表框上的 Format 事件:

#1)。报名活动:

myListBox.Format += myListBox_Format;

#2)。处理事件。将传入的

Value
ListControlConvertEventArgs
属性设置为要为列表项显示的字符串。根据 Microsoft 的事件文档:“在格式化 ListControl 中的每个可见项之前引发 Format 事件”。

private void myListBox_Format(object sender, ListControlConvertEventArgs e)
{
    KeyValuePair<string, int> item = (KeyValuePair<string, int>)e.ListItem;
    e.Value = string.Format("{0}({1})", item.Key, item.Value);
}

5
投票

为了获得适当的长期灵活性,我会尝试使用类型化对象,然后您可以稍后做任何您喜欢的事情,引发事件,更改值,不必使用唯一的键,从列表框中获取真实的对象而不仅仅是格式化的对象字符串

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); }
    }
}

0
投票

您可以迭代字典对象并构建列表框项目。

  foreach (KeyValuePair<string, int> kvp in myDictionary)
  {
      lbx.Items.Add(String.Format("{0}({1})", kvp.Key, kvp.Value.ToString()));
  }

0
投票

实际上,如果您想自定义列表框,请从它派生并覆盖

protected override OnDrawItem

答案 1 将得到您在问题中所述的内容,但如果您想反映对象的变化,最好编写绘图例程,以便它自动反映。

或者您可以更改项目的文本,这也可以达到目的。

不要忘记调用 BeginUpdate() 和 EndUpdate()

© www.soinside.com 2019 - 2024. All rights reserved.