Click here to Skip to main content
Rate this: bad
good
Please Sign up or sign in to vote.
hi,
 
I'm trying to test threading using datagridview.
The scenario is:
 
1- A form has (button1), (datagridview1).
2- Once I click (button1) a thread will start and start adding rows until I click again the (button1).
 
I did it like this:
 
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Threading;
 

private void button1_Click(object sender, EventArgs e)
        {
            
 
            Thread thread = new Thread(new ThreadStart(WorkThreadFunction));
            if (thread.ThreadState == ThreadState.Running)
            {
                thread.Abort();
                return;
            }
            thread.Start();
        }
public void WorkThreadFunction()
        {
            try
            {
                dataGridView1.Rows.Add(new object[] { "test" });
 
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
 

 
But unfortunately, it didn't work and I got an error:
Cross-thread operation not valid
 

 
Please help me with an easy tips (edit my code if you can) because I'm not that much experienced with such things.
 

Thanks,
Posted 21-Jun-12 9:55am
Edited 21-Jun-12 9:56am
v2

1 solution

Rate this: bad
good
Please Sign up or sign in to vote.

Solution 1

The DataGridView is on one thread. Then you create another thread to start making the rows. That second thread can't talk to the objects on the first. If the purpose of this was to play around with threading, I think you need to find some other way. Any control that a user sees on the form is going to be on a separate thread and therefore you will have cross-threading issues.
 
If you are a beginner in threading concepts, you might want to start by playing around with a BackgroundWorker[^]
 
Here[^] is an article about how to use one.
 
If you want to learn about doing threading manually, try google[^] for some tutorials to start with.
 
Hope this helps.
  Permalink  
Comments
yasser_ja at 22-Jun-12 5:04am
   
I googled it already and I got confused.
I need to make this code running then I'll be able to understand.
Simple things will be easier.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
0 OriginalGriff 339
1 DineshMaind 95
2 Sergey Alexandrovich Kryukov 94
3 majid torfi 85
4 kbrandwijk 75
0 Zubair MCA 55
1 OriginalGriff 55
2 sankarsan parida 55
3 harshavardhan12345678 45
4 Sandeep Londhe 45


Advertise | Privacy | Mobile
Web01 | 2.8.140827.1 | Last Updated 21 Jun 2012
Copyright © CodeProject, 1999-2014
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100