我在编码中实现了两个Combobox。第一个组合框包含城市名称,第二个组合框包含该城市的POI。现在我想在这两个组合框之间实现if else语句。假设我选择第一个组合框,Button只会启用第一个组合框,然后如果我选择第二个组合框,那么Button将适用于第二个组合框。我不知道怎么做。我的代码就像这样
public void Download_Click(object sender, EventArgs e)
{
// if combox1 select
// all function will work for combobox 1
//else if combobox2 select
//combobbox1 disabled and all function will work for combobx2
}
最初我创建了类来设置像这样的
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);
}
}
}
然后在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>());
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());
}
}
}
这意味着combobox2依赖于combobox1。它将给出与combobox1
相对应的地名然后终于在form1.cs按钮1我试图做这个像这样的
public Form1()
{
InitializeComponent();
PlaceList.Combo_list = comboBox1;
PlaceList.List();
LoadKeys();
}
private void button1_Click(object sender, EventArgs e)
{
if (comboBox1.SelectedIndex != 0)
{
ShortText.txt1 = richTextBox1;
ShortText.shortText(comboBox1.Text);
}
else if (comboBox2.SelectedIndex != 0)
{
ShortText.txt1 = richTextBox1;
ShortText.shortText(comboBox2.Text);
}
else
{
MessageBox.Show("Error");
}
答案 0 :(得分:0)
检查每个组合框的选定索引是否为默认值。不是默认值的是您使用的那个。例如,如果默认值为索引0:
if(combo1.SelectedIndex != 0){
//do something
}
else if(combo2.SelectedIndex != 0) {
//do something else
}
else {
// Error: You need to select something!
}