I have a form and there is no control.I am trying get the controls from Database so my project is slow i thinks i can use threading but I get a error.
void Form_Load(object sender,EventArgs e)
{
SqlDataAdapter adap=new SqlDataAdapter("Select * from MyControls");
DataTable dt=new DataTable();
adap.Fiil(dt);
foreach(DataRow dr in dt.Rows)
{
ThreadStart ts=delegate{ Sample1(dr) };
Thread th=new Thread(ts);
th.start();
}
}
public void Sample1(DataRow dr)
{
this.Invoke(new AddControlsDelegate(AddControls),new object[] {dr } );
}
public void AddControls(DataRow dr)
{
TextBox tx=new TextBox();
tx.Name=dr["Id"].ToString();
this.Controls.Add(tx);
}
public delegate void AddControlsDelegate(DataRow dr);
I am tryin with this code .But it dont work.It adding same control twice time,3 time,4 time
Where is the my wrong?
thanks
You are closing over the loop variable:
You are creating a closure of the loop variable, not its value at the time – since the thread will be only started a little time later, the loop has completed and each thread will use the value of the loop variable at that time, which will be the last row.
Instead create a local variable within the loop and use it in your delegate:
Also see “Closing over the loop variable considered harmful”