【问题标题】:How to clear DataGridView so that new data can fill the cells?如何清除 DataGridView 以便新数据可以填充单元格?
【发布时间】:2012-04-12 18:15:24
【问题描述】:

我正在使用 C# 和 SQL Server 处理我的一个小项目,但我想不出一种方法来清除 DataGridView 中的单元格,以便新数据可以填充单元格。我正在使用参数(例如列中的值)加载数据。例如,我想为某个作者加载所有书籍,然后我想为另一个作者加载所有书籍。由于 DataGridView 没有被清除,所以第二作者的书籍只是加载到先前数据行的下方,并继续这样。

我希望能够在加载新数据之前清除 DataGridView,这样当我单击所谓的“加载数据”按钮时,它可以是我看到的唯一数据。

目前,我的代码或多或少是这样的:

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

如果我为 author1 点击“加载数据”,然后点击 author2,然后再次点击 author1,DataGridView 的外观简化版本:

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

我可以在查询之前添加一段代码来删除 DataGridView 中找到的所有先前数据吗?

【问题讨论】:

    标签: c# datagridview


    【解决方案1】:
    【解决方案2】:

    在添加新行之前,您是否尝试过 table_dataGridView.DataSource = nulltable_dataGridView.Rows.Clear()

    由于您的 table_dataGridView 已绑定到数据源,因此删除现有行的正确代码应该是;

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

    【讨论】:

    • DataSet.Clear(); 的建议对我有用。不过,谢谢您的意见。
    【解决方案3】:

    这对我有用

            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(object sender, EventArgs e) { dt.清除(); GridView1.DataSource = dt; GridView1.DataBind(); }

    【讨论】:

      【解决方案4】:

      您为什么不尝试将 DataSource 设置为 null,例如 table_dataGridView.DataSource=null

      【讨论】:

      • 那行不通。但是DataSet.Clear(); 的建议奏效了。
      【解决方案5】:

      您提供的代码应该会从 DataGridView 中删除以前的数据,并将其替换为新数据。
      问题可能是您将行附加到您的DataTable。你能检查ds1.Tables["table"] 是否只包含你需要的数据吗?

      【讨论】:

        【解决方案6】:

        事件点击添加

        BindingSource.AddNew();

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2021-01-13
          • 2015-03-29
          • 2017-08-30
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-06-04
          • 1970-01-01
          相关资源
          最近更新 更多