简体   繁体   English

.AddCopy在数据绑定的datagridview中

[英].AddCopy in a databound datagridview

I'm creating a program to track our company's IT assets. 我正在创建一个程序来跟踪我们公司的IT资产。 Each item gets its own row so we can individually track where it is and who has it. 每个项目都有自己的行,因此我们可以分别跟踪它的位置和拥有者。 I want to give the user the option to copy and duplicate rows, so they don't have to type in the exact same thing for 50 power cords. 我想为用户提供复制和复制行的选项,因此他们不必为50条电源线键入完全相同的内容。 When I try to use datagridview.rows.addcopy, I get an error message saying that rows cannot be programatically added to a control that is databound. 当我尝试使用datagridview.rows.addcopy时,出现一条错误消息,提示无法以编程方式将行添加到数据绑定的控件中。 Are there any ways around this? 有什么办法解决吗?

You may set the DataGridView.DataSource to a DataTable. 您可以将DataGridView.DataSource设置为DataTable。 Then, when a user selects a row in the datagridview, the content should be first added to the datatable as a new row and again set the datagridview.datasource to this datatable, the change will be reflected. 然后,当用户在datagridview中选择一行时,应首先将内容作为新行添加到datatable中,然后再次将datagridview.datasource设置为此数据表,以反映更改。 Other than that you should write code to update the underlying table in the database. 除此之外,您还应该编写代码来更新数据库中的基础表。

It is assumed the datagridview (dgv) has its DataSource set to a DataTable dt. 假定datagridview(dgv)的DataSource设置为DataTable dt。

code: you can invoke this method as: copyRow(dgv.CurrentRow); 代码:您可以通过以下方式调用此方法:copyRow(dgv.CurrentRow);

private void copyRow(Int32 irow)
{
    DataRow dr = dt.Rows[irow];
    //if you have a unique identifier for this row, then 
    //before adding as a new row , generate a new id 
    //replace the current id in this row with this new value
    //assuming 0 element of dr has the unique id, set dr[0] = <new id>;
    dt.Rows.Add(dr);
    //write code to submit the changes done to DataTable, back to database

    dgv.DataSource = dt;

}

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

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