【问题标题】:call a dictionary from another class to main class and set its value to combobox从另一个类调用字典到主类并将其值设置为组合框
【发布时间】: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&lt;string&gt;()) 行,因为您在下一行覆盖它的值。
  • 我将键设置为第一个组合框,现在我想为第二个组合框设置值。我在描述中提到的列表。
  • 问题不是关于“你期望得到什么”,而是你得到什么 INSTEAD - 特别是:当你到达 eventhalnder 时,poi 的内容是什么?
  • poiPlace() 不会从任何地方调用。这是正确的还是我错过了什么?
  • @Martin 我在答案部分修改了我的代码。我想要做的是我已经在第一个组合框中设置了城市名称。然后我制作了一个文本文件,其中包含包含在第一个组合框中的城市名称和该城市的地名。现在我制作了一个字典,将城市名称设置为键,将地名设置为值。我想根据第一个组合框的键更改第二个组合框。我在答案部分修改了我的代码。请看一看。

标签: c# dictionary methods combobox selectedindexchanged


【解决方案1】:

你不要在任何地方调用poiPlace,这会适当地设置poi-dictionary。我想你必须写一些类似的东西

POI poi1 = new POI();
poi1.poiList()

代替

POI poi1 =new POI();
poi1.List();

编辑:您还必须提供一种将数据从字典中获取到表单的机制,方法是使字典本身 public(强烈不推荐)或使用以下方法:

在你的POI-class 中添加这两个方法:

public bool ContainsKey(string key) { return this.poi.ContainsKey(key) ; }
public List<string> GetValue(string key) { return this.poi[key]; }

现在可以在您的表单中使用这两种方法:

if (poi1.ContainsKey(txt))
{
    List<string> points = poi1.GetValue(txt);
    Combo_list2.Items.Clear();
    Combo_list2.Items.AddRange(points.ToArray());
}

【讨论】:

  • 我在答案部分修改了我的代码。但是弓它在选择索引更改方法中显示 poi1 错误
  • 非常感谢。这正是我想做的。
猜你喜欢
  • 1970-01-01
  • 2014-10-31
  • 1970-01-01
  • 2021-08-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多