【发布时间】:2016-02-03 21:07:46
【问题描述】:
当我尝试将文本框中的新名称和数字添加到字典中,然后尝试将字典的内容添加到 listBox 中时,所有先前的条目都是相同的。就像我添加“Bob Johnson 42”、“Jim Smith 33”、“Peter White 21”一样。当我把它放在 ListBox 中时,它会显示为: 彼得怀特 21 彼得怀特 21 彼得怀特 21
我做错了什么? 这是代码。
private void button1_Click(object sender, EventArgs e)
{
String name = this.textBox1.Text;
int testNumber = int.Parse(textBox2.Text);
submittedTests.Add(this.textBox1.Text, testNumber);
foreach (var x in submittedTests)
{
listBox1.Items.Add(name + " " + testNumber);
}
}
【问题讨论】:
-
您需要从您的字典中访问
Key和Value,目前您正在访问您的局部变量。listBox1.Items.Add(x.Key + " " + x.Value);应该修复它
标签: c# dictionary visual-studio-2015