473,659 Members | 3,117 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Getting a subset of DataRows from a DataTable

I have a DataTable from which I only need a certain range of the DataRows.
What I would like to do is copy a range of rows from one DataTable to a new
DataTable like the following:

For i As Integer = start To last
table1.Rows.Add (table2.Rows(i) )
Next

However, the code above gives an error saying the DataRow is already used in
another DataTable. Is there any easy way to copy a DataRow from one
DataTable to another? I tried to use the CopyTo method, but I was having
some trouble doing that. Can somebody help me here?
--
Nathan Sokalski
nj********@hotm ail.com
http://www.nathansokalski.com/
Nov 17 '07 #1
9 9331
Nathan,

As you use versions later then 2003 you can use very simple use the
Overloaded DataView.ToTabl e for that.

However you cannot create a table and then add rows. A row exist from items
which are described in the column collection from a table. In the datarow is
stored what table contains the collection, therefore your error message.

Cor

Nov 17 '07 #2
Hi Nathan,

Try this method:
table1.Rows.Add (table2.Rows[i].ItemArray);

--
Miha Markic [MVP C#, INETA Country Leader for Slovenia]
RightHand .NET consulting & development www.rthand.com
Blog: http://cs.rthand.com/blogs/blog_with_righthand/

"Nathan Sokalski" <nj********@hot mail.comwrote in message
news:OL******** ******@TK2MSFTN GP03.phx.gbl...
>I have a DataTable from which I only need a certain range of the DataRows.
What I would like to do is copy a range of rows from one DataTable to a new
DataTable like the following:

For i As Integer = start To last
table1.Rows.Add (table2.Rows(i) )
Next

However, the code above gives an error saying the DataRow is already used
in another DataTable. Is there any easy way to copy a DataRow from one
DataTable to another? I tried to use the CopyTo method, but I was having
some trouble doing that. Can somebody help me here?
--
Nathan Sokalski
nj********@hotm ail.com
http://www.nathansokalski.com/
Nov 17 '07 #3
On 17 Nob, 17:53, "Miha Markic" <miha at rthand comwrote:
Hi Nathan,

Try this method:
table1.Rows.Add (table2.Rows[i].ItemArray);

--
Miha Markic [MVP C#, INETA Country Leader for Slovenia]
RightHand .NET consulting & developmentwww. rthand.com
Blog:http://cs.rthand.com/blogs/blog_with_righthand/

"Nathan Sokalski" <njsokal...@hot mail.comwrote in message

news:OL******** ******@TK2MSFTN GP03.phx.gbl...
I have a DataTable from which I only need a certain range of the DataRows.
What I would like to do is copy a range of rows from one DataTable to a new
DataTable like the following:
For i As Integer = start To last
table1.Rows.Add (table2.Rows(i) )
Next
However, the code above gives an error saying the DataRow is already used
in another DataTable. Is there any easy way to copy a DataRow from one
DataTable to another? I tried to use the CopyTo method, but I was having
some trouble doing that. Can somebody help me here?
--
Nathan Sokalski
njsokal...@hotm ail.com
http://www.nathansokalski.com/
try this (untested):

dim table2 as new datatable

table2 = table1.clone()
for i = start to last
table2.importro w(table1.rows(i ))
next

hope this helps
Nov 17 '07 #4
diego,

Is this not much easier?
dt2 = dt1.DefaultView .ToTable()

(The defaultview is the default dataview)

Cor

Nov 17 '07 #5
Is this not much easier?
dt2 = dt1.DefaultView .ToTable()

No because this wil copy all rows and the TS stated he wanted to have a
subset of the original rows
I just insert the itemarray from the source row in the destination table
this is afaik the shortest way and can be used in a table select or for each
loop without anny problems .

regards

michel
"Cor Ligthert[MVP]" <no************ @planet.nlschre ef in bericht
news:A9******** *************** ***********@mic rosoft.com...
diego,

Is this not much easier?
dt2 = dt1.DefaultView .ToTable()

(The defaultview is the default dataview)

Cor

Nov 17 '07 #6
Michel,

With the defaultview you can select the rows by the rowfilter and the
columns by the overloading part of the ToTable, can you do it with less
commands?

Cor

Nov 17 '07 #7
AFAIK

This wil not work so easy as you tell it Cor as the Totable and then
select method wil return a datarow array

so then you must loop through the datarow array , then another problem
occurs couse the select method returns not a strongly typed datarow so you
must typecast the object
or just asume the datarows are the same and use in your loop construct also
the standard datarow object ,so some more coding is required to get it
functional

and that against this
For i As Integer = start To last

table1.Rows.Add (table2.Rows(i) .ItemArray)

Next

i guess is hart to beat in terms of perfomance , readability and used
resources

Or i might be missing something here , always ready to learn something new
so correct me if i am wrong

regards

Michel

"Cor Ligthert[MVP]" <no************ @planet.nlschre ef in bericht
news:21******** *************** ***********@mic rosoft.com...
Michel,

With the defaultview you can select the rows by the rowfilter and the
columns by the overloading part of the ToTable, can you do it with less
commands?

Cor

Nov 17 '07 #8
Michael,

The "DataTable.Sele ct is returning an array of datarows.

The dataview.ToTabl e is returning a datatable.

You saw my sample, I seldom do this for this kind of messages, but I made it
in the designer, that is impossible if it cannot return a table.

However because it is you I extend it a little bit.

Private Sub Form1_Load(ByVa l sender As System .Object, _
ByVal e As System.EventArg s) Handles MyBase.Load

'To create a sample table
Dim dt1 As New DataTable
Dim dtc1 As New DataColumn("Mic hel")
Dim dtc2 As New DataColumn("Cor ")
dt1.Columns.Add (dtc1)
dt1.Columns.Add (dtc2)
For i = 1 To 10
Dim dr As DataRow = dt1.NewRow
dr(0) = i.ToString & i.ToString
dr(1) = i
dt1.Rows.Add(dr )
Next
'End of building Datatable

'Therefore all you need is
dt1.DefaultView .RowFilter = "Michel 33 And Michel < 66"
Dim dt2 As DataTable = dt1.DefaultView .ToTable(False, "Cor")
'To Show in a Grid
DataGridView1.D ataSource = dt2
End Sub

The True would make a distinct table, I used 2008 beta, this overload is in
my mind not in VS2005 I thought that you need in that he new tablename as
first parameter. However you can do it for the rest exactly like this.

:-)

Cor

Nov 17 '07 #9
for i as integer = start to last
table1.ImportRo w(table2.Rows(i ))
Next

"Nathan Sokalski" <nj********@hot mail.comwrote in message
news:OL******** ******@TK2MSFTN GP03.phx.gbl...
>I have a DataTable from which I only need a certain range of the DataRows.
What I would like to do is copy a range of rows from one DataTable to a new
DataTable like the following:

For i As Integer = start To last
table1.Rows.Add (table2.Rows(i) )
Next

However, the code above gives an error saying the DataRow is already used
in another DataTable. Is there any easy way to copy a DataRow from one
DataTable to another? I tried to use the CopyTo method, but I was having
some trouble doing that. Can somebody help me here?
--
Nathan Sokalski
nj********@hotm ail.com
http://www.nathansokalski.com/

Nov 17 '07 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
1398
by: Prince | last post by:
hi all, I need to insert a datarows collection from a datatable into a datagrid?can anyone tell me how to do??? Thanx in advance..
1
1579
by: psb | last post by:
I thought this was weird?? is this a bug in framework 1.0??? (1.0 is the version I am running against) --------------------------- dim dtAll as new datatable dim dtTmp as datatable dtTmp = LoadDataTable("select top 100 from table...") for i=0 to dtTmp.rows.count -1 ''''ERROR ON THIS LINE''' dtAll.Rows.Add(dtTmp.rows(i))
5
2464
by: Nathan Sokalski | last post by:
I am writing an ASP.NET application in which I need to copy DataRows from one DataTable to another. When I use code such as the following: temprows = nodes.Select("state='PA'") temptable.Clear() For Each row As DataRow In temprows temptable.Rows.Add(row) Next
9
2057
by: Brad | last post by:
I have written some code to manipulate data/records in a MASTER (order header) and DETAIL (order details) tables. What I have written is too extensive to post but essentially trying to: 1. Assign to a datarow (dr1) the first record of the MASTER table 2. Assign to another datarow (dr2) the second record of the MASTER table 3. If dr1.field1 = dr2.field1, then proceed, otherwise do stop 4. Assign to a third datarow (dr3) the first record...
3
11494
by: creator_bob | last post by:
How do I create an array of datarows from a sorted list? I put a bunch of datarows into a sorted list to sort them. Then I got an array of the sorted elements. However, I cannot typecast them. I get an invalid cast error. I notice that in the debugger, that arrays of datarows are listed as {Length=xx}, but my arrays are listed as {system.array} and refuse to typecast. Public Class mySortedList Inherits SortedList
3
2647
by: H | last post by:
I have a dataset with Customers, Orders, and Items tables. It has datarelations set between Customers-Orders and Orders-Items It has foreignkeyconstraints with update/delete rules set to cascade for Orders & Items. The dataset is filled with Customers and their related Orders and their related Items. What is the most efficient way to create a second dataset that is a subset of the main dataset, but only has data for Customer_id = "1"
3
1370
by: zhshqzyc | last post by:
remove other DataRows from your DataTable Hi, I want to display the top three rows of the table. So I just want to remove the other rows. Suppose the datas are not from a database. How to do it? Thanks
8
2013
by: jehugaleahsa | last post by:
Hello: We wrote an entire application where we add our DataRows to our DataTables immediately. However, we have to shut off our constraints to do this. We would like to use detached DataRows to circumvent this. What do you normally do to track detached DataRows? Is there a way to retrieve them? or do I have to stored them in some temporary location? Thanks for any input!
0
8428
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8335
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8851
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8747
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
7356
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5649
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
1
2752
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
1976
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1737
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.