I’m working on a little project of mine in C# and SQL Server and I can’t figure out a way to clear out the cells in a DataGridView so that new data can fill the cells. I am loading the data with arguments such as a value in a column. For example, I want to load all the books for a certain Author, and then I want to load all the books for another author. Since the DataGridView isn’t cleared, the books of the second author are just loaded below the rows of the previous data and it continues like this.
I want to be able to clear the DataGridView before the new data is loaded so it can be the only data I see when I click my so-called “Load data” button.
At the moment, this is what my code looks like more or less:
SqlConnection connect;
DataSet ds1 = new DataSet();
SqlDataAdapter da;
connect = new SqlConnection();
connect.ConnectionString = "Data Source=THEPC-PC\\SQLExpress;Initial Catalog=TheDatabase;Integrated Security=True";
string sql = "Select * from table WHERE author = 'BookAuthor'";
da = new SqlDataAdapter(sql, connect);
da.Fill(ds1, "table");
table_dataGridView.AutoGenerateColumns = false;
table_dataGridView.DataSource = ds1.Tables["table"];
connect.Open();
connect.Close();
A simplified version on how the DataGridView looks if I clicked “Load data” for author1 and then for author2 and then for author1 again:
------------------------
| author1 | bookONE |
------------------------
| author1 | bookTWO |
------------------------
| author2 | bookA |
------------------------
| author1 | bookONE |
------------------------
| author1 | bookTWO |
------------------------
Is there a piece of code I can add before the query that will erase all previous data found in the DataGridView?
DataSet.Clear();
http://msdn.microsoft.com/en-us/library/system.data.dataset.clear.aspx