[英]how to dynamically add combobox in windows forms(C#) and bound it to a column of a table in sql database
我的 windows 窗體有一個添加按鈕,每次單擊后都會向窗體添加一個組合框。 問題是,我無法在運行時將其綁定到表列。 使用現有的數據綁定源會在所有組合框中選擇相同的值。 我正在用 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 上放置了一個組合框和一個按鈕,並設置了組合的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 表中的下一列(但是沒有邊界檢查)。
如您所見,這是非常簡單的事情。 希望這可以幫助。
好的,這里是代碼的變體,可以幫助您解決您在此答案的評論中提出的其他問題。
它假設您有一個帶有按鈕的Form和一個帶有表Employees的DataSet 。 單擊按鈕時,它會創建一個組合,並用數據填充它(員工的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;
}
這非常接近您的要求,或者很容易適應以滿足您的期望。 享受並請選擇一個答案作為接受的答案。 謝謝!
需要先在父窗口中添加控件,然后再設置數據源。
ComboBox ocbNext = new ComboBox();
this.Controls.Add(ocbNext);
ocbNext.DisplayMember = "sub_name";
ocbNext.ValueMember = "sub_name";
ocbNext.DataSource = this.dummysubjectBindingSource;
選項 1:用字符串填充組合框:
this.comboBox1.Items.Add("Syed");
this.comboBox1.Items.Add("Baqar");
選項 2:用字符串數組填充組合框:
this.comboBox1.Items.AddRange(new object[] { "Syed", "Baqar" });
如果您在 clickevent 中創建一個新的本地 ComboBox 變量應該沒問題。 如果您為 ComboBox 使用全局變量,這可能會解釋您的問題。 但是如果沒有樣本你是如何做的,就很難看出真正發生了什么,所以認為這只是一個粗略的猜測
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.