C#Winform省市联动下拉框
效果如下:代码:
//定义字典
Dictionary<string, string> Address = new Dictionary<string, string>();
void loadData()
{
//这是你要添加的数据
//也可以选择动态添加但是考虑到数据不多不影响性能就这么做了
Address.Add("绵阳", "四川");
Address.Add("成都", "四川");
Address.Add("广汉", "四川");
Address.Add("南京", "江苏");
Address.Add("扬州", "江苏");
Address.Add("无锡", "江苏");
Address.Add("珠海", "广州");
Address.Add("东莞", "广州");
Address.Add("深圳", "广州");
Address.Add("上海", "直辖市");
//通过循环值添加进省会下拉框
foreach (string province in Address.Values)
{
//判断下 避免重复添加省会名
if (!comboBoxEdit1.Properties.Items.Contains(province))
comboBoxEdit1.Properties.Items.Add(province);
}
//省会下拉框选择索引方法
private void comboBoxEdit1_SelectedIndexChanged(object sender, EventArgs e)
{
//添加之前先把市级下拉框清空 避免追加数据
//你也可以选择动态添加
comboBoxEdit2.Properties.Items.Clear();
//通过值查找键值
foreach (KeyValuePair<string, string> kvp in Address)
{
if (kvp.Value.Equals(comboBoxEdit1.SelectedItem.ToString()))
{
comboBoxEdit2.Properties.Items.Add(kvp.Key);
}
}
}
页:
[1]