Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/asp.net/36.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何在动态添加数据之前清除dataGridView行以前的数据。。。。?_C#_Asp.net_Datagridview_Windows Forms Designer - Fatal编程技术网

C# 如何在动态添加数据之前清除dataGridView行以前的数据。。。。?

C# 如何在动态添加数据之前清除dataGridView行以前的数据。。。。?,c#,asp.net,datagridview,windows-forms-designer,C#,Asp.net,Datagridview,Windows Forms Designer,当我把这段代码放在pgm之前的for循环中时,它甚至没有在“GridView”中给出任何数据,直到输出pgm 我试着说: for(int c =1;c<=author.books.count;c++) { string author = author.name.ToString(); string author = author.book_name.ToString(); string author = author.published_yea

当我把这段代码放在pgm之前的for循环中时,它甚至没有在“GridView”中给出任何数据,直到输出pgm

我试着说:

 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);
 }
      dataGridView1.Rows.Clear();
和上面一样,它不显示任何数据


请帮助我将xml读入dataTable并将该表与datagridview绑定。在这种情况下,不需要清除行内容


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

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

所以你应该这样做。不需要if语句

删除此语句

     if (this.dataGridView1.DataSource != null)
      {
          this.dataGridView1.DataSource = null;
      }
     else
     {
       this.dataGridView1.Rows.Clear();
     }
你的代码应该是这样的

 if (this.dataGridView1.DataSource != null)

这是清除行的正确方法。

在这种情况下使用
ObservableCollection
。您能给出一个示例代码吗……….我对c不熟悉,我在for循环之前使用了下面的循环。即使它添加到以前的数据中。。。。。。。。对于(int row_count=dataGridView1.Rows.count;row_count>=0;row_count--){dataGridView1.Rows.RemoveAt(row_count-1);},如果将datagridview绑定到上述语句中不起作用
      this.dataGridView1.DataSource = null;
      this.dataGridView1.Rows.Clear();