【问题标题】:How to get key and value from text file and set value in combobox如何从文本文件中获取键和值并在组合框中设置值
【发布时间】:2015-12-15 13:58:28
【问题描述】:

我的窗口窗体应用程序中有两个组合框。第一个组合框显示我已经从 xls 文件的数据库中获得的国家/地区的城市名称。组合框像这样显示城市名称 -

     Berlin
     Munich 
     Stuttgart //etc.

现在我编写了一个文本文件,其中包含该地点的兴趣点列表。我的文本文件看起来像

Berlin,Berlin Wall,Brandenburg Gate,Reichstag Building
Munich,Nymphenburg palace,Museum Island,Marienplatz
Stuttgart,Old Castle,Staatsgalerie Stuttgart,schlossplatz stuttgart //etc

现在我希望当一个地方出现在第一个组合框中时,所有 POI 项目将在第二个组合框中以列表形式自动生成,就像我点击柏林时第二个组合框会显示

  Berlin Wall
  Brandenburg Gate
  Reichstag Building

但我不确定如何继续执行此操作。

我的代码是-

ComboBox 1 按以下方式填写

 class PlaceList
   {
      public static ComboBox Combo_list = new ComboBox();
      public static DataGridView dataTable = new DataGridView();

      public static void List()
      {

        var startPath = Application.StartupPath;
        string folderName = Path.Combine(startPath, "POI_List");
        System.IO.Directory.CreateDirectory(folderName);
        string SavedfileName = "POI_list.json";
        var Saving_path = Path.Combine(folderName, SavedfileName);

        string fileName = "Zensus_Gemeinden_org.xlsx";
        var path = Path.Combine(startPath, fileName);

        String name = "Gemeinden_31.12.2011_Vergleich";
        String constr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" +
                       path + ";Extended Properties='Excel 12.0 XML;HDR=YES;';";

        OleDbConnection con = new OleDbConnection(constr);
        OleDbCommand oconn = new OleDbCommand("Select [3] as City,[4] as Population, * From [" + name + "$D7:E11300] Where [4] > 10000", con);
        con.Open();

        OleDbDataAdapter sda = new OleDbDataAdapter(oconn);
        DataTable data = new DataTable();

        sda.Fill(data);
        dataTable.DataSource = data;



        for (int i = 0; i < data.Rows.Count; i++)
        {
            Combo_list.Items.Add(data.Rows[i]["City"]);
        }
        string Place_Json = "Place_List:" + JsonConvert.SerializeObject(data, Formatting.Indented);
        File.WriteAllText(Saving_path, Place_Json);

       }
    }
  }

然后我从 From1.cs 中调用它就像这样

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

        InitializeComponent();
        PlaceList.Combo_list = comboBox1;


    }
 }

【问题讨论】:

  • 您需要加载文件并在字典中逐行构建一个条目,其中键是带有城市名称的字符串,值是带有 POI 的字符串列表。然后,当您从组合中选择一个城市时,只需使用该字符串作为关键字来搜索您的字典
  • 谢谢但我是处理这个问题的新手,你有什么例子吗? @史蒂夫
  • 您为什么要复制@Steve 对问题的部分答案?
  • @nickc 当然,您是该站点的新手,并且您可能没有意识到以这种方式更改问题会使正确评估答案变得困难。请不要这样做,如果您对收到的答案有任何疑问,请随时评论要求澄清的答案

标签: c# dictionary combobox key


【解决方案1】:

您需要加载文件并在字典中逐行构建一个条目,其中键是带有城市名称的字符串,值是带有 POI 的字符串列表。然后,当您从组合中选择一个城市时,只需使用该字符串作为关键字来搜索您的字典

例如,这是一个完整的示例,您可以使用 LinqPAD 进行测试,并展示如何读取您的 txt 文件并构建一个全局变量,让您的兴趣点以城市名称为关键字

Form f;
ComboBox cboCities;
ComboBox cboPoi;
Dictionary<string, List<string>> poi = new Dictionary<string, List<string>>();
void Main()
{
    f = new Form();
    cboCities = new ComboBox();
    cboCities.DropDownStyle = ComboBoxStyle.DropDownList;
    cboCities.Items.AddRange(new string[] { "Berlin", "Munich", "Stuttgart"});
    cboCities.SelectedIndexChanged += cboCities_SelectedIndexChanged;
    f.Controls.Add(cboCities);
    cboPoi = new ComboBox();
    cboPoi.Location = new System.Drawing.Point(0, 30);
    f.Controls.Add(cboPoi);
    foreach (string line in File.ReadLines(@"D:\temp\poi.txt"))
    {
        string[] parts = line.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
        poi.Add(parts[0], new List<string>(parts.Skip(1)));
    }
    f.ShowDialog();
}
void cboCities_SelectedIndexChanged(object sender, EventArgs e)
{
    string txt = cboCities.SelectedItem.ToString();
    if (poi.ContainsKey(txt))
    {
        List<string> points = poi[txt];
        cboPoi.Items.Clear();
        cboPoi.Text = string.Empty;
        cboPoi.Items.AddRange(points.ToArray());
    }
}

【讨论】:

  • 您好,它不工作。我试了几次。最初它只工作了 1 次,之后它停止显示任何值。 @史蒂夫
  • 奇怪,我刚刚用一个简单的应用程序进行了测试,并按预期工作。您能否在事件处理程序中放置一个断点,并在每次更改城市组合的内容时检查代码是否正确调用?
  • 您的城市组合是否使用下拉列表样式?
  • 是的。我从 .xls 文件中得到了一个很长的列表,它是下拉列表样式。
  • 那么你应该使用 SelectedItem 而不是 Text 属性,但在此之前检查 null
【解决方案2】:

这是我编辑的答案:

 private void button1_Click(object sender, EventArgs e)
    {

        LoadKeys();

    }
    Dictionary<string, List<string>> poi = new Dictionary<string, List<string>>();
    private void LoadKeys()
    {

       foreach (string line in File.ReadLines("TextFile1.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));
                }

    }

    void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (comboBox1.SelectedItem != null)
        {
            string txt = comboBox1.SelectedItem.ToString();
            if (poi.ContainsKey(txt))
            {
                List<string> points = poi[txt];
                comboBox2.Items.Clear();
                comboBox2.Items.AddRange(points.ToArray());
            }
        }
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-06-08
    • 1970-01-01
    • 2019-11-27
    • 1970-01-01
    • 2015-01-31
    • 2011-03-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多