【发布时间】: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