C#无法将DataGridView另存为png,因为应用一直挂起

问题描述

我正在尝试将DataGridView保存为png。 我向DataGridView添加一个按钮,该按钮应该执行此操作,但是我总是会收到此错误

跨线程操作无效:控制“ phrasesDataGridView”是从其他线程(不是在其上创建的线程)访问的 在这条线上: phrasesDataGridView.DrawToBitmap(位图,新的System.Drawing.Rectangle(0,0,this.phrasesDataGridView.Width,this.phrasesDataGridView.Height));

我得到的错误是跨线程操作无效:控制'phrasesDataGridView'是从不是在其上创建线程的线程访问的

我尝试在此处遵循一些建议: enter link description here 但是无论我如何尝试,我都不会再收到错误,但我的应用程序会挂起。

没有任何更改的原始代码如下:

  private void SavePng_Click(object sender,EventArgs e)
    {
        if (phrasesDataGridView.Rows.Count > 0)
        {
            var t = new Thread((ThreadStart)(() =>
            {
                var sfd = new SaveFileDialog();
                sfd.Filter = "PNG (*.png)|*.png";
                sfd.FileName = "Phrases.png";
                var fileError = false;
                if (sfd.ShowDialog() == DialogResult.OK)
                {
                    if (File.Exists(sfd.FileName))
                    {
                        try
                        {
                            File.Delete(sfd.FileName);
                        }
                        catch (IOException ex)
                        {
                            fileError = true;
                            Console.Beep();
                            MessageBox.Show("Unable to write to file." + ex.Message);
                        }
                    }

                    if (!fileError)
                    {
                        try
                        {
                            var bitmap = new Bitmap(this.phrasesDataGridView.Width,this.phrasesDataGridView.Height);
                            phrasesDataGridView.DrawToBitmap(bitmap,new System.Drawing.Rectangle(0,this.phrasesDataGridView.Width,this.phrasesDataGridView.Height));
                            bitmap.Save(sfd.FileName);
                            Console.WriteLine(sfd.FileName);

                        }
                        catch (Exception ex)
                        {
                            Console.Beep();
                        }
                    }
                }

            }));
            t.SetApartmentState(ApartmentState.STA);
            t.Start();
            t.Join();
        }
        else
        {
            MessageBox.Show("Unable to save Phrase file","Save as PDF");
        }
    }

它在我尝试添加的行中挂起:

                        phrasesDataGridView.Invoke(dt => dt.DrawToBitmap(bitmap,this.phrasesDataGridView.Height)));

此扩展程序:

 public static class Extensions
    {
        public static void Invoke<TControlType>(this TControlType control,Action<TControlType> del)
            where TControlType : Control
        {
            if (control.Invokerequired)
                control.Invoke(new Action(() => del(control)));
            else
                del(control);
        }
    }

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)