datagridview从线程添加行 [英] datagridview adding rows from a thread

查看:240
本文介绍了datagridview从线程添加行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我正在尝试使用datagridview测试线程.
情况是:

1-表单具有(button1),(datagridview1).
2-单击(button1)后,线程将启动并开始添加行,直到再次单击(button1).

我是这样的:



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,

推荐答案

DataGridView在一个线程上.然后,创建另一个线程以开始制作行.第二个线程无法与第一个线程交谈.如果这样做的目的是为了解决线程问题,那么我认为您需要找到其他方法.用户在表单上看到的任何控件都将在单独的线程上,因此您将遇到跨线程问题.

如果您是线程概念的初学者,则可能要先尝试使用 BackgroundWorker [^ ]

此处 [ google [
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.


这篇关于datagridview从线程添加行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆