【问题标题】:Error when removing a column from DataGridView从 DataGridView 中删除列时出错
【发布时间】:2015-08-19 20:13:12
【问题描述】:

我正在尝试根据用户CheckBox 的选择将DataGridView 导出为PDF。

当我从DataGridView 的“副本”中删除一些列时,我收到一个一般错误:

未处理的类型异常 在 mscorlib.dll 中发生“system.reflection.targetinvocationexception”

附加信息:异常已由一个目标引发 调用。

这是我的代码:

var gridViewToExport = dataGridView1; 

foreach (var columnIndex in columnsToRemove) //columnsToRemove is a List of int
{
    gridViewToExport.Columns.Remove(gridViewToExport.Columns[columnIndex]); //This is the line where the error is thrown.
}

更多代码:

var gridViewToExport = new DataGridView();
await Services.LoadDataAsync(gridViewToExport);

foreach (var columnIndex in columnsToRemove.OrderByDescending(x => x))
{
    gridViewToExport.Columns.RemoveAt(columnIndex); 
}
try
{
    string contactInfo = metroTextBoxContact.Text;
    Services.ContactInfo = contactInfo;
    Services.ExportToPdf(gridViewToExport);
}
catch (Exception ex)
{
    MessageBox.Show(ex.Message);
}

LoadDataAsync Function

    public async static Task LoadDataAsync(DataGridView gridView)
    {
        const string getDataQuerySql = @"My query string";

        using (var connection = new SqlConnection(ConnectionString))
        {
            if (connection.State == ConnectionState.Closed)
                await connection.OpenAsync();

            var command = new SqlCommand
            {
                Connection = connection, 
                CommandType = CommandType.Text, 
                CommandText = getDataQuerySql,
                CommandTimeout = 20000
            };

            using (var adapter = new SqlDataAdapter(command))
            {
                var table = new DataTable();

                adapter.Fill(table);
                gridView.DataSource = table;
                gridView.Update();
                gridView.Refresh();
            }
        }
    }

【问题讨论】:

  • 该事件可能在元素完全加载或引用仍未设置之前引发,因此异常

标签: c# .net winforms datagridview


【解决方案1】:

您应该在 gridview 上按降序删除列

   foreach (var columnIndex in columnsToRemove.OrderByDescending(x => x)
   {
        gridViewToExport.Columns.RemoveAt(columnIndex); 
   }

如果按照递增的顺序删除列,最终可能会导致索引指向不再存在的列

【讨论】:

  • 这很有意义..但仍然无法正常工作..再次出现同样的错误。
  • 尝试使用 RemoveAt 而不是 Remove
  • 还是同样的错误?现在有不同的消息?除非这里有多线程工作的情况,否则这应该可以工作。您是否在主应用程序的同一线程中调用此代码?
  • 可能问题的根源在于 LoadDataAsync 方法内部。你能添加那个代码吗?
  • 当然.. 现在检查.. 我删除了查询字符串,因为它很长。请注意,当我在表单 DataGridView 上显示数据时,该函数可以正常工作。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-12-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多