How to clear DataGridView so that new data can fill cells?

I am working on a small project of mine in C # and SQL Server, and I cannot figure out how to clear the cells in the DataGridView so that new data can fill the cells. I load data with arguments such as the value in the column. For example, I want to download all the books for a specific author, and then I want to download all the books for another author. Since the DataGridView is not cleared, the books of the second author are loaded only under the lines of the previous data, and it continues as follows.

I want to clear the DataGridView before the new data is loaded, so this may be the only data that I see when I click on the so-called "Load data" button.

At the moment, my code looks 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();

, DataGridView, " " 1, 2, 1:

------------------------
| author1 |  bookONE   |
------------------------
| author1 |  bookTWO   |
------------------------
| author2 |   bookA    |
------------------------
| author1 |  bookONE   |
------------------------
| author1 |  bookTWO   |
------------------------

, , , DataGridView?

+3
6

table_dataGridView.DataSource = null table_dataGridView.Rows.Clear() ?

table_dataGridView DataSource, :

if (table_dataGridView.DataSource != null)
{
     table_dataGridView.DataSource = null;
}
else
{
    table_dataGridView.Rows.Clear();
}
+5

        cl.OpenCon();
        String data = "select ID,Name,Price from Items";
        SqlCommand ncmd = new SqlCommand(data);
        ncmd.Connection = cl.ReturnCon();
        SqlDataReader rs = ncmd.ExecuteReader();
        dt = new DataTable();
        dt.Load(rs);
        GridView1.DataSource = dt;
        GridView1.DataBind();
        cl.CloseCon();

protected void Clear_Click1 ( , EventArgs e)       {           dt.Clear();           GridView1.DataSource = dt;           GridView1.DataBind();       }

+2
source

Why aren't you trying to set the DataSource as null, like table_dataGridView.DataSource = null

+1
source

The code you provided should erase the previous data from DataGridViewand replace it with new data.
The problem may be that you are adding lines to yours DataTable. Can you check if it contains ds1.Tables["table"]only the data that you need?

+1
source

in event click add

BindingSource.AddNew ();

0
source

All Articles