Nuthssall
Nuthssall

Reputation: 11

Error when removing a column from DataGridView

I'm trying to export a DataGridView to PDF, based on user CheckBox selection.

When I remove some columns from the 'copy' of the DataGridView, I get a general error:

An unhandled exception of type 'system.reflection.targetinvocationexception' occurred in mscorlib.dll

Additional information: exception has been thrown by the target of an invocation.

This is my code:

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.
}

More code:

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();
            }
        }
    }

Upvotes: 1

Views: 509

Answers (1)

Steve
Steve

Reputation: 216293

You should work on your gridview removing columns in descending order

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

If you remove the columns following an increasing order you could end up with indexes pointing to columns no more existing

Upvotes: 1

Related Questions