从另一个类中的另一个线程向datagridview添加一行

时间:2017-05-28 01:21:24

标签: c#

我有一个datagridview,我正在尝试添加数据,我尝试了以下没有错误,但没有添加数据:

mywindowform grid = new mywindowform();
grid.datagridview.rows.add("hello", "it's me");

我也尝试过:

mywindowform grid = new mywindowform();
grid.datagridview.Invoke(new Action(delegate ()
{
    grid.datagridview.Rows.Add("hello", "it's me");
}));

我收到以下错误:

  

System.InvalidOperationException:在创建窗口句柄之前,无法在控件上调用Invoke或BeginInvoke。'

如果我将以下内容添加到主窗体中,它可以工作,但我需要通过类来完成它,以分离代码:

datagridview.Invoke(new Action(delegate ()
{
    datagridview.Rows.Add("hello", "it's me");
}));

那么,如何从使用后台工作者的类中向我的datagridview添加行..我已经查看了stackoverflow,并且他们已经推荐调用,我做了,但是上面得到了错误。

使用gridview的表单:

public Form1()
{
    InitializeComponent();
}

private async Task core()
{
    articles article = new articles();

    articles.StatusTextChanged += (sender, text) =>
    {
        Invoke((MethodInvoker)
        delegate {  
            status.Text = text;
        });
    };

    await article.GenerateArticles();
}

private void backgroundworker_DoWork(object sender, DoWorkEventArgs e)
{
    core();
}

我的班级档案:

class articles
{
    public static event EventHandler<string> StatusTextChanged;

    Form1 grid = new Form1();


    private async Task CreateRow()
    {
        //Fixed window handle issue.
        if (!grid.IsHandleCreated)
        {
            grid.CreateControl();
            MessageBox.Show("1");
            grid.UploadQueue.Invoke((MethodInvoker)
                delegate
                {
                    grid.UploadQueue.Rows.Add("ff", "f", "Generating Audio");
                });
        }
    }

    public async Task GenerateArticles()
    {
        try
        {
            // Get the settings for our database
            DataConnection.DefaultSettings = new MySettings();

            await FindArticles();

        }
        catch (Exception ex)
        {
            // Exception
            StatusTextChanged?.Invoke(this, "123" + ex.Message);
        }
    }
    public async Task FindArticles()
    {
        try
        {
            //update label in main form
            StatusTextChanged?.Invoke(this, "Adding to datagrid view.");

            // Add to datagridview
            CreateRow().Wait();

        }
    }
}

1 个答案:

答案 0 :(得分:0)

如错误所述,您无法调用尚未创建窗口句柄的控件。请参阅:https://msdn.microsoft.com/en-us/library/system.windows.forms.control.createcontrol(v=vs.110).aspx

具体来说:

  

简单地调用控件的构造函数不会创建句柄。

您只需显示窗口即可解决此问题,该窗口需要创建句柄:

mywindowform grid = new mywindowform();
grid.Show();
grid.datagridview.Invoke(new Action(delegate ()
{
    grid.datagridview.Rows.Add("hello", "it's me");
}));

或者,如果您还不想显示该窗口,可以抓住窗口handle,这会强制它创建一个窗口:

mywindowform grid = new mywindowform();
IntPtr gridHandle = grid.Handle;
grid.datagridview.Invoke(new Action(delegate ()
{
    grid.datagridview.Rows.Add("hello", "it's me");
}));