我在解决方案中添加了一个 DataSet,并在设计器中删除了 Employees 表(来自 Northwind),它自动创建了 employeesBindingSource。我在表单上放置了一个组合框和一个按钮,并设置了组合的 DataSource 和 DataMember。然后我处理了一些事件:
private void Form1_Load(object sender, EventArgs e)
{
this.employeesTableAdapter.Fill(this.dS.Employees);
}
private int _i = 0;
private void button1_Click(object sender, EventArgs e)
{
ComboBox combo = new ComboBox();
combo.DataSource = this.employeesBindingSource;
combo.DisplayMember = this.dS.Tables[0].Columns[++_i].ColumnName;
combo.Location = new Point(comboBox1.Location.X, comboBox1.Location.Y + comboBox1.Height * _i);
this.Controls.Add(combo);
}
因此,在每次点击时,都会在表单上动态添加一个新的组合,就在前一个组合的正下方。该组合还绑定到Employees 表中的下一列(但是没有边界检查)。
如您所见,这是非常简单的事情。希望这可以帮助。
好的,这是代码的变体,可以帮助您解决您在此答案的 cmets 中提出的其他问题。
假设您有一个带有按钮的Form 和一个带有Employees 表的DataSet。单击按钮时,它会创建一个组合,并用数据填充它(Employees 的 Name 列)。每次添加一个组合时,它都会获得自己的数据副本(这对于能够一次从一个组合中删除项目很重要)。然后,每次您在组合中选择一个值时,该组合都会被禁用,并且其他组合在其列表中没有该选定值。
private int _i = 0;
private void button1_Click(object sender, EventArgs e)
{
DataSet dataS = dS.Clone();
this.employeesTableAdapter.Fill((DS.EmployeesDataTable)dataS.Tables[0]);
BindingSource bindSource = new BindingSource(dataS, "Employees");
ComboBox combo = new ComboBox();
combo.Name = this.dS.Tables[0].Columns[0].ColumnName + (++_i).ToString();
combo.DataSource = bindSource;
combo.DisplayMember = this.dS.Tables[0].Columns[1].ColumnName; //This column is the Name of Employee
combo.Location = new Point(button1.Location.X, button1.Location.Y + combo.Height * _i);
combo.SelectedIndexChanged += new EventHandler(comboBox_SelectedIndexChanged);
this.Controls.Add(combo);
}
private void comboBox_SelectedIndexChanged(object sender, EventArgs e)
{
foreach (Control ctrl in this.Controls)
{
if (ctrl is ComboBox && ctrl != sender && ctrl.Enabled)
{
((BindingSource)((ComboBox)ctrl).DataSource).RemoveAt(((ComboBox)sender).SelectedIndex);
}
}
((ComboBox)sender).Enabled = false;
}
这非常接近您的要求,或者很容易适应您的期望。享受并请选择一个答案作为接受的答案。谢谢!