Guest User

Guest User

  • Tech Writer
  • 3
  • 707

C# Threading Error

Mar 15 2018 3:08 AM
Any other ways to do it in C# ? I've been working for it since yesterday but i cant solve this problem. . I want this code to be executed in the background using another thread so that my main thread or UI thread will be responsive, I am creating a dynamic label using loop. . Thanks.
  1. private void Contact_Load(object sender, EventArgs e)  
  2. {  
  3. Thread loadContact = new Thread(new ThreadStart(loadContacts));  
  4. loadContact.Start();  
  5. }  
  6. private void loadContacts()  
  7. {  
  8. Label l = null; ContactPanel.Controls.Clear();  
  9. dt.Clear();  
  10. dataConnection.Open();  
  11. using (var messages = new SqlCommand("SELECT * FROM BasicInfo ", dataConnection))  
  12. {  
  13. da.SelectCommand = messages; da.Fill(dt);  
  14. SqlDataReader rd = messages.ExecuteReader();  
  15. string Fname, Lname,Fullname,Id;  
  16. if (rd.HasRows)  
  17. {  
  18. for (int i = 0; i < dt.Rows.Count; i++)  
  19. {  
  20. Point location = Point.Empty;  
  21. DataRow dr = dt.Rows[i];  
  22. Id = dr["_Id"].ToString();  
  23. Fname = dr["_Fname"].ToString();  
  24. Lname = dr["_Lname"].ToString();  
  25. Fullname = Fname + Lname;  
  26. l = addLabel(i);  
  27. ContactPanel.Controls.Add(l);  
  28. l.Text = Fname + " " + Lname; l.Name = Lname + i;  
  29. l.Click += new EventHandler(this.labelClick);  
  30. }  
  31. }  
  32. else { }  
  33. Thread.Sleep(5000);  
  34. }  
  35. dataConnection.Close();  
  36. }  
  37. public void labelClick(object sender, EventArgs e)  
  38. {  
  39. Label currentLabel = (Label)sender;  
  40. currentLabel.BackColor = Color.Gray;  
  41. MessageBox.Show(currentLabel.Text);  
  42. MainForm MainForm = new MainForm();  
  43. MainForm.Show();  
  44. this.Close();  
  45. MainForm.TxtReciever.Text = currentLabel.Text;  
  46. }  
  47. public Label addLabel(int i)  
  48. {  
  49. Label l = new Label();  
  50. l.Name = "Date" + i.ToString();  
  51. l.BackColor = Color.SteelBlue;  
  52. l.ForeColor = Color.White;  
  53. //l.BackColor = Color.White;  
  54. l.Font = new Font("Segoe UI", 12, FontStyle.Regular);  
  55. l.TextAlign = ContentAlignment.MiddleCenter;  
  56. l.Margin = new Padding(5,3,3,3);  
  57. l.Width = 255;  
  58. l.Height = 53;  
  59. return l;  
  60. }

Answers (2)