【发布时间】:2016-01-14 10:59:15
【问题描述】:
我制作了一个文本文件,其中包含一个城市名称和该城市许多有趣的地方名称。我希望当城市名称出现在第一个组合框上时,第二个组合框将自动显示所有地名。
为此,在第一步中,我使用从大型 .xls 文件中获得的城市名称填充了第一个组合框。然后我用该城市的城市和地名制作了文本文件。看起来像这样-
Flensburg;Nordertor;Naval Academy Mürwik;Flensburg Firth
Kiel;Laboe Naval Memorial;Zoological Museum of Kiel University
Lübeck;Holstentor;St. Mary's Church, Lübeck;Passat (ship)
我在一个单独的方法中创建字典,现在我想在主窗体中调用这个方法。好吧,我正在以这种方式尝试。但它实际上并没有工作。
对于数据输入我写了如下代码-
public class POI
{
Dictionary<string, List<string>> poi = new Dictionary<string, List<string>>();
public void poiPlace()
{
foreach (string line in File.ReadLines("POIList.txt"))
{
string[] parts = line.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
poi.Add(parts[0], new List<string>());
poi[parts[0]] = new List<string>(parts.Skip(1));
}
}
现在我想在主窗体中调用它
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
POI poi1 =new POI();
poi1.List();
}
public void Combo_list_SelectedIndexChanged(object sender, EventArgs e)
{
if (Combo_list1.SelectedItem != null)
{
string txt = Combo_list1.SelectedItem.ToString();
if (poi.ContainsKey(txt))
{
List<string> points = poi[txt];
Combo_list2.Items.Clear();
Combo_list2.Items.AddRange(points.ToArray());
}
}
}
它根本不起作用。
【问题讨论】:
-
“不工作”具体是什么意思?调试时
poi的内容是什么?顺便说一句:可以省略poi.Add(parts[0], new List<string>())行,因为您在下一行覆盖它的值。 -
我将键设置为第一个组合框,现在我想为第二个组合框设置值。我在描述中提到的列表。
-
问题不是关于“你期望得到什么”,而是你得到什么 INSTEAD - 特别是:当你到达 eventhalnder 时,
poi的内容是什么? -
poiPlace() 不会从任何地方调用。这是正确的还是我错过了什么?
-
@Martin 我在答案部分修改了我的代码。我想要做的是我已经在第一个组合框中设置了城市名称。然后我制作了一个文本文件,其中包含包含在第一个组合框中的城市名称和该城市的地名。现在我制作了一个字典,将城市名称设置为键,将地名设置为值。我想根据第一个组合框的键更改第二个组合框。我在答案部分修改了我的代码。请看一看。
标签: c# dictionary methods combobox selectedindexchanged