How to display a dictionary which contains a list

2019-08-29 03:25发布

问题:

I currently have a dictionary which contains a key value and a list associated with that key. I have read How to bind Dictionary to ListBox in winforms and when I try to implement that it just displays the key value.

What I am trying to do is have two separate listboxs. In box 1 you select the key value, when this happens box 2 displays the list. The current code is below:

var xmlDoc2 = new XmlDocument();
xmlDoc2.Load(textBox1.Text);
Dictionary<string, List<string>> dict = new Dictionary<string, List<string>>(StringComparer.OrdinalIgnoreCase);

var node = xmlDoc2.SelectNodes("pdml/packet/proto[@name='ip']/@showname");

foreach (XmlAttribute attribute1 in node)
 {
   string ip = attribute1.Value;
   var arr = ip.Split(); var src = arr[5]; var dst = arr[8];

   List<string> l;
   if (!dict.TryGetValue(src, out l))
     {
        dict[src] = l = new List<string>();
     }

   l.Add(dst);

   listBoxSRC.DataSource = new BindingSource(dict, null);
   listBoxSRC.DisplayMember = "Value";
   listBoxSRC.ValueMember = "Key";

  }

What this does so far is displays the key value in listBoxSRC, which is fine. What I need to do is display the list in listBoxDST.

I also looked at using ListView to rectify this issue but I couldn't figure out how it worked.

I know there should be a listBoxSRC_SelectedIndexChange somewhere but I keep getting 'dict doesn't appear in this context' errors.

Thanks

回答1:

I jotted up something real quick with a pair of list boxes. Just make any form with a pair listboxes in it and wire up the event to try it yourself. By using the SelectedItem and casting it as the KeyValuePair that it is, you don't have to declare that dictionary outside of the method scope, as shown below.

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();

        listBox1.DataSource = new BindingSource(new Dictionary<string, List<string>>
        {
            {"Four-Legged Mammals", new List<string>{"Cats", "Dogs", "Pigs"}},
            {"Two-Legged Mammals", new List<string>{"Humans", "Chimps", "Apes"}}
        }, null);

        listBox1.DisplayMember = "Value";
        listBox1.ValueMember = "Key";
    }

    private void listBox1_SelectedValueChanged(object sender, EventArgs e)
    {
        if (listBox1.SelectedItem != null)
        {
            var keyValue = (KeyValuePair<string, List<String>>) listBox1.SelectedItem;
            listBox2.DataSource = keyValue.Value;
        }
        else
        {
            listBox2.DataSource = null;
        }
    }