简体   繁体   English

C#DATAGRIDVIEW选择行并显示选择的行

[英]C# DATAGRIDVIEW select rows and display selected rows

My datagrid view is populated with multiple rows of data, I want to be able to select multiple rows in my datagridview and then update the datagridview to only display the selected rows but i am getting errors 我的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);





    }

When i select the rows and click the update button i am getting the error "Rows cannot be programmatically added to the DataGridView's rows collection when the control is data-bound." 当我选择行并单击更新按钮时,出现错误“控件绑定数据时行无法以编程方式添加到DataGridView的行集合中”。

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

I have tried looking at the exception help for this but cannot make sense of it Thanks for your help 我曾尝试查看异常帮助,但无法理解它。谢谢您的帮助

If I remember correctly the datagridview must not be data bound in order to manipulate the rows. 如果我没记错的话,不能将datagridview绑定到数据中以操纵行。

I believe that I solved this problem a couple months back but I can't get access to my projects right now. 我相信几个月前就解决了这个问题,但现在无法访问我的项目。

I think you can do it by finding and removing the rows from the data source and then refresh the datagridview 我认为您可以通过从数据源中查找并删除行,然后刷新datagridview来做到这一点

(personal advice: take a short break 10-15 mins and go back at it with a clearer mind) (个人建议:稍事休息10-15分钟,然后以清晰的心态回到原处)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM