如有两个ComboBox,希望点击第一个的选中项时,另外一个的内容作出相应的变化。
方法一:
<span style="font-size:14px;"><span style="font-size:14px;">using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace testCB
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
comboBox2.Items.Clear();
if(comboBox1.SelectedItem=="植被")
{
comboBox2.Items.Add("草地");
comboBox2.Items.Add("林地");
}
else if(comboBox1.SelectedIndex==1)
{
comboBox2.Items.Add("gengdi01");
comboBox2.Items.Add("gengdi02");
comboBox2.Items.Add("gengdi3");
}
else if (comboBox1.SelectedIndex == 2)
{
comboBox2.Items.Add("shandi01");
comboBox2.Items.Add("shandi02");
comboBox2.Items.Add("shandi3");
}
}
private void Form1_Load(object sender, EventArgs e)
{
comboBox1.Items.Add("植被");
comboBox1.Items.Add("耕地");
comboBox1.Items.Add("山地");
}
}
}</span></span>
效果:
方法二(绑定到List<string>数据源):
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace testCB
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
//comboBox2.Items.Clear();
if(comboBox1.SelectedIndex==0)
{
List<string> listCB01_0 = new List<string>();
listCB01_0.AddRange(new string[] { "Apple", "Pear", "Banana", "Watermalen" });
comboBox2.DataSource = listCB01_0;
}
else if(comboBox1.SelectedIndex==1)
{
List<string> listCB01_1 = new List<string>();
listCB01_1.AddRange(new string[] { "豆角", "蒜苔", "彩椒", "青菜" });
comboBox2.DataSource = listCB01_1;
}
else if (comboBox1.SelectedIndex == 2)
{
List<string> listCB01_2 = new List<string>();
listCB01_2.AddRange(new string[] { "猪肉", "鸡肉", "羊肉", "牛肉", "鱼" });
comboBox2.DataSource = listCB01_2;
}
}
private void Form1_Load(object sender, EventArgs e)
{
List<string> listCB01 = new List<string>();
listCB01.Add("水果");
listCB01.Add("蔬菜");
listCB01.Add("肉");
comboBox1.DataSource = listCB01;
}
}
}
效果: