Click here to Skip to main content
13,197,200 members (58,072 online)
Rate this:
Please Sign up or sign in to vote.

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)
public void WorkThreadFunction()
                dataGridView1.Rows.Add(new object[] { "test" });
            catch (Exception ex)

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.

Posted 21-Jun-12 9:55am
Updated 21-Jun-12 9:56am

1 solution

Rate this: bad
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.
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)

  Print Answers RSS
Top Experts
Last 24hrsThis month

Advertise | Privacy |
Web03 | 2.8.171020.1 | Last Updated 21 Jun 2012
Copyright © CodeProject, 1999-2017
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