如何删除DataGridView中的所有行?

时间:2013-11-13 16:09:55

标签: c# datagridview delete-row

这是代码:

         BindingSource bs = new BindingSource();


       DataTable tbl(string sql)
        {

        OracleConnection con = new OracleConnection(connectionstring);
        OracleDataAdapter adp = new OracleDataAdapter(sql, con);
        DataSet ds = new DataSet();
        adp.Fill(ds, "tbl");
        return ds.Tables["tbl"];
        }
 void GetData()
  {

   bs.DataSource = Class1.tbl("select USER_ID   ,EMP_NAME as pName,EMP_MOBILE from TBLUSERS");
            datagridview1.Columns[0].DataPropertyName = "USER_ID";
            datagridview1.Columns[1].DataPropertyName = "pName";
            datagridview1.Columns[2].DataPropertyName = "EMP_MOBILE";
            datagridview1.DataSource = bs;
 }

  void ClearAllRows()
    {
          datagridview1.Rows.Clear();
   //The error occurs here 
    }

此处发生错误 如何在DataGridView中删除所有行? 我的DataGridView是BindingSource

2 个答案:

答案 0 :(得分:4)

您可以将DataGridView DataSource设置为null,而不是清除行。

替换为:

datagridview1.Rows.Clear();

以下:

datagridview1.DataSource=null;

答案 1 :(得分:0)

while (dataGridView1.Rows.Count>0)
{
    dataGridView1.Rows.Remove(dataGridView1.Rows[0]);
}