在POI类中的代码中,我想实现一些方法,首先它将从.xls文件中获取数据。然后,它将在datagridview表中显示城市和人口名称。现在,从datagridview表中,它将只使用将显示在第一个组合框中的城市名称。然后,如果有人点击第一个组合框项目,它将在第二个组合框上显示该城市的一些地方。然而,代码是我写的。现在我很困惑如何从Form1.cs中调用它,以及它将如何工作,因为目前它根本不工作。
我的POI类代码是
public class POI
{
Form f;
public static ComboBox Combo_list1 = new ComboBox();
public static ComboBox Combo_list2 = new ComboBox();
public static DataGridView dataTable = new DataGridView();
Dictionary<string, List<string>> poi = new Dictionary<string, List<string>>();
public void List(Form f)
{
f = new Form();
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_list1.Items.Add(data.Rows[i]["City"]);
}
string Place_Json = "Place_List:" + JsonConvert.SerializeObject(data, Formatting.Indented);
File.WriteAllText(Saving_path, Place_Json);
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 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());
}
}
}
}
我想在form1.cs类中调用这两个方法。但它不起作用。Form1.cs看起来像这样-
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
POI.Combo_list1 = comboBox1;
POI.dataTable = dataGridView1;
//POI.List();
//POI
}
private void button1_Click(object sender, EventArgs e)
{
}
}
抱歉代码太长了。非常感谢您的回答。
按照当前编写代码的方式,您需要实例化POI
对象才能调用这些方法。您可以这样做,也可以使这些方法成为静态的。
POI.List()当然不会工作,因为POI不是静态类。相反,您应该初始化POI类对象
POI instaceObj = new POI();
instanceObj.List();
此外,我认为您应该改进您的代码。希望得到帮助。