I load some data into a datagridview, I use a loop to do that.

When I need to load new data I get rid of old data like so...

foreach (DataGridViewRow row in dataGridView1.Rows)
                {
                    dataGridView1.Rows.Remove(row); ;
                }

Now I try to add new rows, because new data might different number of rows and columns, but the control does not show as if it's just gone.
Does anyone know what I might be doing wrong?

Recommended Answers

All 3 Replies

I had dataGridView1.Dispose()
I removed that, and now the new data is being input but the old columns are still present too.

(edit)
I tried adding

foreach (DataGridViewColumn column in dataGridView1.Columns)
                {
                    dataGridView1.Columns.Remove(column);
                }

But get the following error
Collection was modified; enumeration operation may not execute.

Rows and Columns are collections in datagridview control. Both collections have Clear method:

    dataGridView1.Rows.Clear();
    dataGridView1.Columns.Clear();

Now you should have an "empty" datagridview control.

HTH

Thanks Teme64, I did see the Clear method but used it wrong much like I did with the above Remove method.

Your explanation did indeed help, it is exactly what I needed.
Much appreciated, and solved.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.