【问题标题】:Clone/Copy, Edit then Add Dataset Row克隆/复制,编辑然后添加数据集行
【发布时间】:2016-01-18 19:50:11
【问题描述】:

背景

我有一个 sql 数据库绑定数据集,它是 Datagridview (dgv) 的数据源。我想允许用户通过右键单击行标题并从上下文菜单条中选择一个选项来复制和粘贴一行。我已经做到了。

问题

如何复制、编辑然后添加一行?

我目前拥有的代码,复制、编辑旧行和新行然后添加?

代码片段

  //Get row
            var newrow = JoblistDataSet.Tables["Joblist"].Rows[rowIndex];

 //Duplicate row
            var copy = newrow;

    //Get next id of Identity Column of database
            var lastid =  getLastID() +1 ;

  //Sets the ID column of row to the nextID 
            copy[0] = lastid;

  JoblistDataSet.Tables["Joblist"].ImportRow(copy);

【问题讨论】:

  • var copy = newrow; 不会复制该行,而只是将引用复制到另一个变量。所以改变一个的属性,会改变另一个的属性。

标签: c# datagridview dataset datarow


【解决方案1】:

如果你想从前一行复制一整行,这是一种可能的方法

// Row to copy from
DataRow dr = JoblistDataSet.Tables["Joblist"].Rows[rowIndex];

// Row that receives the values from source
DataRow newrow = JoblistDataSet.Tables["Joblist"].NewRow();

// Copy the ItemArray of the source row to the destination row
// Note that this is not a reference copy.
// Internally a new object array is created when you _get_ the ItemArray
newrow.ItemArray = dr.ItemArray;

// Change whateever you need to change
newrow[0] = 99;

// Add the new row into the datatable collection
JoblistDataSet.Tables["Joblist"].Rows.Add(newrow);

【讨论】:

  • 您能解释一下为什么我们使用项目数组吗?不过看起来不错,谢谢。
  • 只是因为 ItemArray 是保留所有行值的属性(即该行的列的值)当您编写 var copy = newrow 您不是在创建新行,而是强制 copy 变量指向 newrow 变量的相同数据。相反,您要求数据表为您创建一个空行(具有相同的架构),然后将前一行的 ItemArray 放在新行中。 DataRow 代码在内部为您制作副本。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-05-25
  • 2020-03-04
  • 2012-04-25
  • 1970-01-01
  • 2018-06-01
  • 1970-01-01
相关资源
最近更新 更多