我目前有两个列表框。一种是存储密钥,第二种是查看与之关联的列表。
以下代码我在第一个listBox中显示了该键,但未能在第二个列表中显示该列表:
public void button1_Click(object sender, EventArgs e)
{
var xmlDoc = new XmlDocument();
xmlDoc.Load(textBox1.Text);
var node = xmlDoc.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];
Dictionary<string, List<string>> dict = new Dictionary<string,List<string>>(StringComparer.OrdinalIgnoreCase);
List<string> listDST;
if (!dict.TryGetValue(src, out listDST))
{
dict[src] = l = new List<string>();
}
l.Add(listDST);
listBoxSRC.DataSource = new BindingSource(dict,null);
listBoxSRC.DisplayMember = "Value";
listBoxSRC.ValueMember = "Key";
}
}
private void listBoxSRC_SelectedIndexChanged(object sender, EventArgs e)
{
if (listBoxSRC.SelectedItem != null)
{
var keyValue = (KeyValuePair<string, List<String>>)listBoxSRC.SelectedItem;
listBoxDST.DataSource = keyValue.Value;
}
else
{
listBoxDST.DataSource = null;
}
}
我已使用调试器检查确保字典列表中包含数据,因此我不确定问题是什么。
有谁可以指出我可能出错的地方?
由于
答案 0 :(得分:0)
试试这个男人
public void button1_Click(object sender, EventArgs e)
{
var xmlDoc = new XmlDocument();
xmlDoc.Load(textBox1.Text);
var node = xmlDoc.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];
Dictionary<string, List<string>> dict = new Dictionary<string,List<string>>(StringComparer.OrdinalIgnoreCase);
List<string> listDST;
if (!dict.TryGetValue(src, out listDST))
{
dict[src] = l = new List<string>();
}
l.Add(listDST);
}
listBoxSRC.DataSource = new BindingSource(dict,null);
listBoxSRC.DisplayMember = "Value";
listBoxSRC.ValueMember = "Key";
}
private void listBoxSRC_SelectedIndexChanged(object sender, EventArgs e)
{
if (listBoxSRC.SelectedItem != null)
{
var keyValue = (KeyValuePair<string, List<String>>)listBoxSRC.SelectedItem;
listBoxDST.DataSource = keyValue.Value;
}
else
{
listBoxDST.DataSource = null;
}
}
答案 1 :(得分:0)
'裸'字符串列表不能用作DataSource
。您需要将它们包装在具有不动产的简单类中。见here
声明一个简单的字符串包装类后:
class aString { public string theString { get; set; }
public aString(string s) { theString = s; }
public override string ToString() {return theString;} }
您可以更改词典以包含List<aString>
,也可以从List<aString>
创建Dictionary Values
:
List<aString> aStringList = dict [src].Select(item => new aString(item) ).ToList();
listBoxDST.DataSource = aStringList ;
ListBox现在可以显示aString.ToString()
值。