Datagridview 异常

Datagridview Exceptions

我有一个带有一个图像列的数据网格视图。 我正在使用带有 textChanged 事件的文本框过滤 datagridview。 在文本框中输入每个键后,我调用函数来更新读取的图像 来自 sqlite 数据库的值并根据条件更新 datagridview 中过滤行上的图像。

例外情况:

Row provided does not belong to this DataGridView control. Parameter name: e.Row

'Index was out of range. Must be non-negative and less than the size of the collection.

以上两个异常经常在同一行代码随机抛出,如下所示

foreach (DataGridViewRow row in DataGridViewAllMusicDark.Rows)

我用thread做到了

                var LockedMusic = db.GetAllLockedMusic();
                Thread thread = new Thread(t =>
                {
                    foreach (var lm in LockedMusic)
                    {
                        foreach (DataGridViewRow row in DataGridViewAllMusicDark.Rows)
                        {
                            if (lm.Key.Equals(row.Cells[2].Value?.ToString()))
                            {
                                ((DataGridViewImageCell)row.Cells[1]).Description = "locked";
                                ((DataGridViewImageCell)row.Cells[1]).Value = Properties.Resources.Dark_Red_PLPS;
                            }
                        }
                    }

                })
                { IsBackground = true };
                thread.Start();

和异步以避免过滤 datagridview 时的性能问题

                var LockedMusic = db.GetAllLockedMusic();
                await Task.Run(() =>
                {
                    CheckForIllegalCrossThreadCalls = false;
                    foreach (var lm in LockedMusic)
                    {
                        foreach (DataGridViewRow row in DataGridViewAllMusicDark.Rows)
                        {
                            if (lm.Key.Equals(row.Cells[2].Value?.ToString()))
                            {
                                ((DataGridViewImageCell)row.Cells[1]).Description = "locked";
                                ((DataGridViewImageCell)row.Cells[1]).Value = Properties.Resources.Dark_Red_PLPS;
                            }
                        }
                    }
                });
            

我正在努力寻找此异常的原因以及解决此问题的方法,如果有人可以帮助我的话

事情不对的提示是您将 CheckForIllegalCrossstThreadCalls 设置为 false。你永远不需要这样做。

当您 UI 发生变化时,您必须仔细选择何时开始通过主线程调用。大部分工作不需要在 UI 线程上发生(读取数据库、进行计算等),因此当用户单击按钮时,启动一个任务来完成所有不影响的事情UI。然后,当这些事情完成后,获取您计算出的信息并通过 BeginInvoke 对其进行处理。当后台有大量数据处理时,让 UI 保持响应是很棘手的。您将不得不尝试触摸 UI 的正确位置。您可能需要以某种方式存储结果,以便可以批量更新 UI。

一般通过,顺序为:

  1. UI 线程发生了一些事情
  2. 启动一个任务或调用一些异步方法在不同的线程上进行处理。 - 这允许 UI 保持 运行-
  3. 工作完成后,获取新信息并使用 UI 更新调用回主线程。

在您的情况下,您可以遍历数据并构建一个列表,其中包含您需要更新的所有字段以及它们应该更新到的内容。然后在 UI 线程上,遍历该列表以将更改应用到 UI.