我正在尝试设计一个简单的Windows窗体应用程序。如果我选择代表国家/地区的组合框。然后如果我选择任何一个国家然后在该国家的另一个组合框状态将来。最后如果我们选择一个州,那么相应的城市将进入另一个组合框。第一次如果我做我的操作它工作正常..但第二次如果我正在做任何修改,然后它连接.. 这是我的代码 -
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (comboBox1.SelectedItem.ToString() == "INDIA")
{
string[] Country = { "Andhra Pradesh",
"Karnataka","Maharashtra"};
comboBox2.Items.AddRange(Country);
}
else if (comboBox1.SelectedItem.ToString() == "USA")
{
comboBox2.Items.AddRange(new string[] { "Alabama",
"Alaska", "Arizona"});
}
else if (comboBox1.SelectedItem.ToString() == "CHAINA")
{
comboBox2.Items.AddRange(new string[] { "Beijing Municipality",
"Tianjin Municipality", "Hebei Province"});
}
}
private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
{
if (comboBox2.SelectedItem.ToString() == "Andhra Pradesh")
{
comboBox3.Items.AddRange(new string[] { "Adilabad","Anantapur","Chittoor","Kakinada","Guntur","Hyderabad", "Khammam","Kurnool","Medak","Nizamabad","Visakhapatnam","Warangal","Eluru"});
}
else if (comboBox2.SelectedItem.ToString() == "Karnataka")
{
comboBox3.Items.AddRange(new string[] { "Bengaluru Urban", "Bengaluru Rural", "Chikkaballapur", "Kolar", "Mysuru" });
}
else if (comboBox2.SelectedItem.ToString() == "Maharashtra")
{
comboBox3.Items.AddRange(new string[] { "Mumbai", "Pune", "Nagpur", "Thane", "Nashik" });
}
else if (comboBox2.SelectedItem.ToString() == "Alabama")
{
comboBox3.Items.AddRange(new string[] { "Margaret","Helena","Southside","Mountain Brook","Vestavia Hills"});
}
else if (comboBox2.SelectedItem.ToString() == "Alaska")
{
comboBox3.Items.AddRange(new string[] { "Anchorage", "Fairbanks", "Juneau", "Sitka", "Ketchikan" });
}
else if (comboBox2.SelectedItem.ToString() == "Arizona")
{
comboBox3.Items.AddRange(new string[] { "Apache Junction", "Avondale", "Benson", "Buckeye", "Bullhead City" });
}
else if (comboBox2.SelectedItem.ToString() == "Beijing Municipality")
{
comboBox3.Items.AddRange(new string[] { "Dongcheng", "Xicheng", "Chaoyang", "Fengtai ", "Miyun " });
}
else if (comboBox2.SelectedItem.ToString() == "Tianjin Municipality")
{
comboBox3.Items.AddRange(new string[] { "Heping", "Hedong", "Xiqing", "Nankai", "Beichen" });
}
else if (comboBox2.SelectedItem.ToString() == "Hebei Province")
{
comboBox3.Items.AddRange(new string[] { "Baoding", "Bazhou", "Chengde", "Handan", "Langfang" });
}
}
请建议我们在代码中应该修改哪些内容?
答案 0 :(得分:0)
由于每次从combobox1(国家/地区)或组合框2(状态)中选择要“重新开始”的内容时,必须首先清除相应事件的辅助组合框,例如:
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
combobox2.Items.Clear();
combobox3.Items.Clear();
. . .
}
private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
{
combobox3.Items.Clear();
. . .
}
此外,最好为控件提供有意义的名称。不要让他们保留默认的通用名称,而是给他们命名,例如comboboxCountries,comboboxStates,comboBoxCities。这将使调试更容易。
最后,最好将地点列表(国家,州和省,市/镇)保存在数据库中,或者至少保留在某种单独维护的列表中。把它们全部放在迷宫般的迷宫中如果挡不住会让你睁大眼睛。