【问题标题】:How do delete All rows at DataGridView?如何删除 DataGridView 中的所有行?
【发布时间】:2013-11-13 16:09:54
【问题描述】:

这是代码:

         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

【问题讨论】:

标签: c# datagridview delete-row


【解决方案1】:

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

替换这个:

datagridview1.Rows.Clear();

以下:

datagridview1.DataSource=null;

【讨论】:

  • 谢谢@Sudhakar
  • 不客气 :) 很高兴为您提供帮助。
  • 不知道为什么需要datagridview1.Rows.Clear()
  • 是的,你是对的,我在清除行的上下文中,只要 DataSource 设置为 null ,Gridview 就会变为 EMPTY。感谢您的宝贵意见,我已经对我的回答进行了更改,谢谢。
  • 当您的 Datagridview 在设计视图中使用“绑定源”设置时,这不起作用。您必须直接处理绑定源。然后清除数据表,或者您需要清除的任何内容。 Dim bs As BindingSource = DirectCast(dgvGrid1.DataSource, BindingSource) Dim ds As DataSet = DirectCast(bs.DataSource, DataSet) Dim dt As DataTable = ds.Tables(0) dt.Rows.Clear()
【解决方案2】:
while (dataGridView1.Rows.Count>0)
{
    dataGridView1.Rows.Remove(dataGridView1.Rows[0]);
}

【讨论】:

    【解决方案3】:

    请执行此代码

    if(dgvItemDetails.Rows.Count>0) {
        do
        {
            dgvItemDetails.Rows.RemoveAt(0);
        }
        while (dgvItemDetails.Rows.Count > 0);
    }
    

    【讨论】:

    • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
    猜你喜欢
    • 1970-01-01
    • 2018-08-08
    • 2016-11-28
    • 1970-01-01
    • 2012-02-05
    • 2017-04-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多