[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 206
  • Last Modified:

Cross-thread Problem

Hi

My Requirement is something like timeControl. What I want my application constantly look at server (at certain interval) and as soon as new record is inserted in Database it Show back in DataGridView. Pl help me
 
        static string conn = "Data Source=192.168.0.18;Initial Catalog=hotel;User ID=sa";
        SqlConnection cn = new SqlConnection(conn);
        SqlDataAdapter ad;
        SqlCommand cmd;
        DataSet ds;
        Thread th;
        public frmDownload()
        {
            InitializeComponent();
            //Control.CheckForIllegalCrossThreadCalls = false;
        }
        private void frmDownload_Load(object sender, EventArgs e)
        {
            cn.Open();
            try
            {
                th = new Thread(new ThreadStart(GetRemoteData1));
                th.Priority = ThreadPriority.Highest;
                th.Start();
            }
            catch (Exception ee)
            {
                MessageBox.Show(ee.Message, "Unable to Connect Remote Server", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

        }
        void GetRemoteData1()    
        {
                cmd = new SqlCommand("SpBookingGuestDetail", cn);
                ad = new SqlDataAdapter(cmd);
                ds = new DataSet();
                ad.Fill(ds);
                DataGridRemote.DataSource = ds.Tables[0];
//////There Error Raises ---- Cross-thread Windows Form Control
                Thread.Sleep(1000);
        }
}

Pl Help
0
HarjeetSingh
Asked:
HarjeetSingh
1 Solution
 
Mike TomlinsonMiddle School Assistant TeacherCommented:
Try...

        void GetRemoteData1()    
        {
                cmd = new SqlCommand("SpBookingGuestDetail", cn);
                ad = new SqlDataAdapter(cmd);
                ds = new DataSet();
                ad.Fill(ds);
                UpdateDataGrid();              
        }

        private delegate void DataGridDelegate();

        private void UpdateDataGrid()
        {
            if (this.InvokeRequired)
            {
                DataGridDelegate dgd = new DataGridDelegate(UpdateDataGrid);
                this.Invoke(dgd);
            }
            else
            {
                DataGridRemote.DataSource = ds.Tables[0];                    
            }
        }
0

Featured Post

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now