【问题标题】:C# DATAGRIDVIEW select rows and display selected rowsC# DATAGRIDVIEW 选择行并显示选定的行
【发布时间】:2015-07-12 09:42:51
【问题描述】:

我的 datagrid 视图填充了多行数据,我希望能够在我的 datagridview 中选择多行,然后更新 datagridview 以仅显示选定的行,但出现错误

  public void btnUpdate_Click(object sender, EventArgs e)
    {


       List<DataGridViewRow> rowCollection = new List<DataGridViewRow>();
       foreach (DataGridViewRow row in dataGridView1.SelectedRows)
       {
           rowCollection.Add(dataGridView1.Rows[row.Index]);
       }

       //dataGridView1.Rows.Clear();




  data.Tables[0].Clear();


      foreach (DataGridViewRow row in rowCollection)
        {
           DataRow r = data.Tables[table].NewRow();
            dataGridView1.Rows.Add(row);
          //write the data in the DataRow and then add the datarow in your datatable
          data.Tables[table].Rows.Add(r);


      }
        CreateGraph(zedGraphControl1);





    }

当我选择行并单击更新按钮时,我收到了错误 “当控件绑定数据时,无法以编程方式将行添加到 DataGridView 的行集合中。”

  • 行 {DataGridViewRow { Index=-1 }} System.Windows.Forms.DataGridViewRow

我已尝试查看此异常帮助,但无法理解 感谢您的帮助

【问题讨论】:

  • 如果DGV是数据绑定的,可以设置DataSource = null解除绑定。收拾桌子时试试看。
  • 另外,请记住 SelectionMode 属性必须设置为 FullRowSelectRowHeaderSelectSelectedRows 属性才能填充选定的行。
  • @steve 我曾尝试使用该方法,但它会删除数据网格视图中的所有值,包括列名
  • @FlipperFlapper 您应该从选定的行中构建新的DataTable 并通过新的DataTable 设置DataGridView.DataSource
  • @agent5566 我该怎么做?看这个屏幕太久了,我的眼睛被炸了

标签: c# select datagridview


【解决方案1】:

如果我没记错的话,datagridview 一定不能绑定数据来操作行。

我相信几个月前我已经解决了这个问题,但我现在无法访问我的项目。

我认为您可以通过从数据源中查找并删除行然后刷新 datagridview 来做到这一点

(个人建议:休息 10-15 分钟,然后以更清晰的头脑重新开始)

【讨论】:

  • 是的,关于休息时间你是对的,我看过之前浏览过的东西
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-01-16
  • 1970-01-01
  • 1970-01-01
  • 2010-11-11
  • 1970-01-01
  • 1970-01-01
  • 2012-03-05
相关资源
最近更新 更多