Click here to Skip to main content
15,881,882 members
Please Sign up or sign in to vote.
5.00/5 (1 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:

C#
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
Updated 21-Jun-12 9:56am
v2

1 solution

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.
 
Share this answer
 
Comments
yasser_ja 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)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900