Changing of selection in manually bound ComboBox
I fill the combobox with the below method and when I change the selection it's changed in all the Comboboxes why?
PowerProjectDBLinqDataContext dataContext =new PowerProjectDBLinqDataContext();
IEnumerable<Winding_Building_typeCombo> ls = dataContext.Winding_Building_typeCombos.ToList();
ComboBox cbx;
for (int i = 1; i <= windingCount; i++)
{
开发者_如何转开发 cbx=((ComboBox)WindingPanel.Controls["winding" + i].Controls["cbxWindingBildingType" + i]);
cbx.ValueMember = "id";
cbx.DisplayMember = "value";
cbx.DataSource = ls;
}
the answer is probably not in this code.;
I imagine its because all iof the combo boxes are using the same reference.
you have probably done something like this
var combo = new ComboBox();
ComboBox cb1 = combo;
ComboBox cb2 = combo;
ComboBox cb3 = combo;
Edit: oops yeah as the other guy said, you are setting them all the use the same data context. Ie when you change the selected value in the datacontext they will all update to reflect their context - ie to select the same row.
cbx.DataSource = ls;
this line is setting them all to the same thing. you need to take a copy of the datacontext in each case so that each combo points to a unique datacontext.
Try this
PowerProjectDBLinqDataContext dataContext =new PowerProjectDBLinqDataContext();
ComboBox cbx;
for (int i = 1; i <= windingCount; i++)
{
IEnumerable<Winding_Building_typeCombo> ls = dataContext.Winding_Building_typeCombos.ToList();
cbx=((ComboBox)WindingPanel.Controls["winding" + i].Controls["cbxWindingBildingType" + i]);
cbx.ValueMember = "id";
cbx.DisplayMember = "value";
cbx.DataSource = ls;
}
I suspect that you have only one instance of cbx control. So each time you are binding your cbx to a data source you are actually overwriting currently existing data binding, and eventually your control will be bound to the last data source only.
I tried this method and it's working I create an image of the list in the place of the Context to save time and memory
PowerProjectDBLinqDataContext dataContext =new PowerProjectDBLinqDataContext();
IEnumerable<Winding_Building_typeCombo> ls = dataContext.Winding_Building_typeCombos.ToList();
ComboBox cbx;
for (int i = 1; i <= windingCount; i++)
{
IEnumerable<Winding_Building_typeCombo> lsCopy = new List<Winding_Building_typeCombo>(ls);
cbx=((ComboBox)WindingPanel.Controls["winding" + i].Controls["cbxWindingBildingType" + i]);
cbx.DataSource = lsCopy;
lsCopy = null;
cbx.ValueMember = "id";
cbx.DisplayMember = "value";
}
精彩评论