我正在尝试根据用户DataGridView
选择将CheckBox
导出为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();
}
}
}
答案 0 :(得分:1)
您应该按照降序删除列的gridview
{{1}}
如果按照递增顺序删除列,最终可能会出现指向不再存在的列的索引