2012-06-29 33 views

回答

12

将它们分别绑定到DataSet1.Table [0]的单独实例。

即)

foreach (Control c in this.Controls) 
{ 
    if (c is ComboBox) 
    { 
     DataTable dtTemp = DataSet1.Tables[0].Copy(); 
     (c as ComboBox).DataSource = dtTemp 
     (c as ComboBox).DisplayMember = "Articles"; 
    } 
} 
+0

Thankyou GrandMaster。解决了。 – Alegro

+0

很高兴我能帮到你。 – GrandMasterFlush

+1

根据ComboBox的数量和DataTable中的数据量,这可能会导致应用程序的内存占用大量增加,这是由于数据的重复。 – cadrell0

6

一个更好的方法是使用一个DataView,以避免重复的数据。另外,如果可以避免,则不要多次投射。

foreach (Control c in this.Controls) 
{ 
    ComboBox comboBox = c as ComboBox; 

    if (comboBox != null) 
    {   
     comboBox.DataSource = new DataView(DataSet1.Tables[0]); 
     comboBox.DisplayMember = "Articles"; 
    } 
} 

编辑

我才意识到你可以用LINQ

foreach (ComboBox comboBox in this.Controls.OfType<ComboBox>()) 
{ 
    comboBox.DataSource = new DataView(DataSet1.Tables[0]); 
    comboBox.DisplayMember = "Articles"; 
} 
+0

这是一个更好的方法来做到这一点。被接受的答案会有更大的内存占用。 – SQLMason

1

更清洁为此,我面临同样的问题,但我与仿制药的工作。我已经使用了组合框的绑定上下文来摆脱这种情况。 (当你不知道绑定列表的大小时非常有用 - 在你的情况下它是5项)

在下面的代码中,DisplayBindItem只是一个包含Key和Value的类。

List<DisplayBindItem> cust = (from x in _db.m01_customers 
      where x.m01_customer_type == CustomerType.Member.GetHashCode() 
      select new DisplayBindItem 
      { 
       Key = x.m01_id.ToString(), 
       Value = x.m01_customer_name 
      }).ToList(); 

    cmbApprover1.BindingContext = new BindingContext(); 
    cmbApprover1.DataSource = cust; 
    cmbApprover1.DisplayMember = "Value"; 
    cmbApprover1.ValueMember = "Key"; 

    //This does the trick :) 
    cmbApprover2.BindingContext = new BindingContext(); 
    cmbApprover2.DataSource = cust ; 
    cmbApprover2.DisplayMember = "Value"; 
    cmbApprover2.ValueMember = "Key"; 

该类供您参考。

public class DisplayBindItem 
    { 
     private string key = string.Empty; 

    public string Key 
    { 
     get { return key; } 
     set { key = value; } 
    } 
    private string value = string.Empty; 

    public string Value 
    { 
     get { return this.value; } 
     set { this.value = value; } 
    } 

    public DisplayBindItem(string k, string val) 
    { 
     this.key = k; 
     this.value = val; 
    } 

    public DisplayBindItem() 
    { } 
} 

如果这能解决您的问题,请标记为答案。

相关问题