如何将数据行添加到已有的数据表中?
我有一个已经填充的数据表。现在我想向该数据表添加几行,但某些行可能已经存在于数据表中。我知道它是不必要的,但这是要求。
我尝试了几件事并得到“该行已存在于该表中:&该行属于其他表”。我也尝试了 importRow ,但我想它会默认避免重复。
有没有办法做到这一点。如果数据表有 7 行,并且我想再添加 3 行,无论它是否已经存在。我的目标是将 10 行发送到调用函数。
或者还有其他方法吗?
更新
使用 rowsToAdd.CopyToDataTable(dsCount.Tables[2], LoadOption.PreserveChanges);
有效,但我不确定这是正确的方法。
I am having an datatable which is already populated. Now i want to add few rows to that datatable ,but some of rows might already exist in the datatable.I know its unneccesary but tht is the requirement.
I tried couple of things and got "the row already exist in this table : & this row belongs to some other table" .I also tried importRow ,but i guess it avoid the duplicates by dafault.
Is there any way to do that .If the datatable has 7 rows and i want to add 3 more rows whether its already exist or not. My goal is to send 10 rows to the calling function .
Or is there any other approach altogether?
UPDATE
UsingrowsToAdd.CopyToDataTable(dsCount.Tables[2], LoadOption.PreserveChanges);
works but I'm not sure it's the proper way.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您可以使用下面的代码在
DataTable
中添加新行You can add new rows in
DataTable
using code below要检查是否有重复项,请尝试
如果您希望能够插入重复行,但又不想引发异常,请将主键设置为唯一的自递增 int,然后您可以插入任意数量的重复项,而无需必须检查表是否包含该值。只要确保有重复就足够了。设置主键的例子有很多,搜索一下即可(msdn 至少有一个)。这是一个例子:
To check for any duplicates try
If you want to be able to insert duplicate rows but do not want to have an exception thrown set-up your primary key as a unique self-incrementing int then you can insert as many duplicates as you feel like without having to check to see if the table contains that value. Just make sure that it would suffice to have duplicates. There are plenty of examples of setting a primary key just search for it (msdn has at least one). Here is an example:
使用 NewRow() 函数创建一个新行。
然后将新行添加到数据表中
Create a new row using the NewRow() function.
Then add your new row to your datatable
我相信如果您只是向表中追加一行,则可以使用 DataTable 的 NewRow() 函数。
这还不够吗?
I believe you can use the NewRow() function of the DataTable if you're simply appending a row to the table.
Will that not suffice?
最直接的方法。花了几个小时尝试其他一切之后。
The most straightforward method. After spending a few hours trying everything else.