如何在动态添加数据之前清除dataGridView行以前的数据....

时间:2012-05-25 07:10:10

标签: c# asp.net datagridview windows-forms-designer

 for(int c =1;c<=author.books.count;c++)             
 {

  string author = author.name.ToString();

  string author = author.book_name.ToString();
  string author = author.published_year.ToString();

  string[] row = new string[]{author, book_name, published_year};
  dataGridView1.Rows.Add(row);
 }

这是我的代码(类似)........我从一个XML文件中获取数据。我的问题是当我选择一位作者在windows_form.after中的gridview中给出数据时,如果我再选择一位作者,则会将附加数据附加到预览数据。我想只显示当前选定的作者数据。

我尝试过:

      dataGridView1.Rows.Clear();

当我把这个代码放在pgm之前for循环时它甚至没有在“GridView”中通过pgm提供任何数据。

我尝试过:

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

同样的方式,它不显示任何数据。

请帮帮我.................

2 个答案:

答案 0 :(得分:2)

如果您的datasource = null正在清算行。这意味着如果已经分配了某些数据源,则不会清除行。你的情况如何?

所以你应该这样做。不需要if声明。

删除此声明

 if (this.dataGridView1.DataSource != null)

,您的代码应如下所示

      this.dataGridView1.DataSource = null;
      this.dataGridView1.Rows.Clear();

这是清除行的正确方法。

答案 1 :(得分:0)

将xml读入dataTable并将表绑定到datagridview。在这种情况下,您不需要清除行内容。

否则,您可以使用datagridview.Rows.RemoveAt(index)datagridview.Rows.Remove(row)