我在代码中创建了两个组合框。第一个我用来表示德国城市名称像弗伦斯堡,基尔,吕贝克。它以组合框的方式显示
Flensburg
Kiel
Lübeck
我从.xls文件中获取此列表。我是一个单独的类来获取此值。我用来获取此值的代码如下
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);
}
}
然后在form1.cs中我称这个城市名称如下
public Form1()
{
InitializeComponent();
PlaceList.Combo_list = comboBox1;
}
这部分对我来说非常合适。现在下一步是阅读一个文本文件,我为每个地方列表写了几个兴趣点
Flensburg,Berlin Wall,Brandenburg Gate,Reichstag Building
Kiel,Nymphenburg palace,Museum Island,Marienplatz
Lübeck,Old Castle,Staatsgalerie Stuttgart,schlossplatz stuttgart
我想根据第一个combobox1的点击获得此值。假如有人点击弗伦斯堡,他可以看到第二个组合框中的每个值。为了得到这个,我在Form1.cs中使用以下代码
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>(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());
}
}
}
但它根本不起作用。它对组合框2没有任何价值。我可以用不同的方式做到这一点。很抱歉有很长的描述。