Easy Question on Dynamically created Control

  • Thread starter Thread starter Ed West
  • Start date Start date
E

Ed West

Hi,

I am dynamically creating Comboboxes and putting them in a panel.
However, they are all referencing the same object! When I change one,
then all of them change. How can I make it so it doesn't do this? I'm
sure this is pretty simple, just can't find the answer. Thanks.

for (int i=0; i < _ds.Tables[0].Columns.Count; i++) {
ComboBox x = new ComboBox();
x.Name = "col" + i.ToString();
x.DataSource = EMRData.DBFieldsDS.Tables[0].DefaultView;
x.DisplayMember = "name";
x.Width = 100;
x.Height = 15;
x.DropDownStyle = ComboBoxStyle.DropDownList ;
x.Location = new Point(x.Width*i + 10, 5);
pnlMapFields.Controls.Add(x);
x = null;
}

any ideas?

-ed
 
Ed,

The reason for this is that they are all accessing the same data source
(EMRData.DBFieldsDS.Tables[0].DefaultView) in the same binding context. If
you want to change this, then assign a new binding context to the control
before you set the data source, like so:

// Set the binding context.
x.BindingContext = new BindingContext();

// Set the data source.
x.DataSource = EMRData.DBFieldsDS.Tables[0].DefaultView;

Or, you could create a new view around the table each time, like so:

// Set the data source.
x.DataSource = new DataView(EMRData.DBFieldsDS.Tables[0]);

The first code has all of the controls work with a separate binding
context, but the same data source, so the change in one, doesn't affect the
change in others.

The second piece of code has all the controls in the same binding
context, but different data sources for each control (the data view ensures
that). You should go with whatever suits your application best.

Hope this helps.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top