如何在Windows窗体(C#)中动态添加combobox并将其绑定到sql数据库中的表的列

我的Windows窗体有一个ADD按钮,每次单击后都会在窗体中添加一个combobox。 问题是,我无法在运行时将其绑定到表列。 使用现有数据绑定源在所有combobox中选择相同的值。 我在C#中编码

这是示例代码:

ComboBox ocbNext = new ComboBox(); //HAVE set the rest of the properties right, the problem is with the databinding ocbNext.DataSource = this.dummysubjectBindingSource; ocbNext.DisplayMember = "sub_name"; ocbNext.ValueMember = "sub_name"; this.Controls.Add(ocbNext); 

我在解决方案中添加了一个DataSet ,并在设计器中删除了Employees表(来自Northwind ),后者自动创建了employeesBindingSource 。 我在Form上放了一个combobox和一个按钮,然后设置了组合的DataSourceDataMember 。 然后我处理了一些事件:

  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表中的下一列(但是没有边界检查)。

如你所见,这很容易。 希望这可以帮助。


好的,所以这里有一个代码的变体,可以帮助你解决你在这个答案的评论中提出的其他问题。

它假设您有一个带有按钮的Form和一个带有Employees表的DataSet 。 在按钮上单击它会创建一个组合,并用数据填充它( EmployeesName列)。 每次添加组合时,它都会获得自己的数据副本(这对于能够一次从一个组合中删除项目非常重要)。 然后,每次在组合中选择一个值时,组合将被禁用,其他组合在其列表中没有选定的值。

  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; } 

这非常接近您的要求,或者很容易适应您的期望。 享受并请选择一个答案作为接受的答案。 谢谢!

选项1:用字符串填充combobox:

 this.comboBox1.Items.Add("Syed"); this.comboBox1.Items.Add("Baqar"); 

选项2:使用字符串数组填充combobox:

 this.comboBox1.Items.AddRange(new object[] { "Syed", "Baqar" }); 

如果在clickevent中创建一个新的本地ComboBox变量,应该没问题。 如果您为ComboBox使用全局变量,这可能会解释您的问题。 但是没有样本你怎么做就很难看出真正发生了什么,所以想想这只是一个粗略的猜测