VB.net 2005 - Clear DataTable / Add NEW Row

I need to clear out the datatable then start adding NEW Rows...but I'm getting an error after I clear the datatable and set my NewRow I get...BeginEdit() will allow creation of new data in this row...

How do I do that?
Here is my current code:
            MyDataTable.Rows.Clear()
            For iCount As Int16 = 0 To FoundRows.GetUpperBound(0)
                Dim MyDataRow As DataRow = MyDataTable.NewRow()
                MyDataRow("UserName") = FoundRows(iCount)(0)
                MyDataRow("FirstName") = FoundRows(iCount)(2)
                MyDataRow("LastName") = FoundRows(iCount)(3)
                MyDataRow("ProfileName") = FoundRows(iCount)(1)
                MyDataRow("JobTitle") = FoundRows(iCount)(4)
                MyDataRow("EMail") = FoundRows(iCount)(5)
                MyDataTable.Rows.Add(MyDataRow)
                MyDataRow = MyDataTable.NewRow()
            Next
smithmrkAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

it_saigeDeveloperCommented:
This works fine for me:
Module Module1
	ReadOnly people As New List(Of Person) From _
	 { _
	  New Person() With {.ID = 0, .Name = "Joe", .Birthdate = DateTime.Now.AddDays(-900), .IsWorking = True}, _
	  New Person() With {.ID = 1, .Name = "Joe", .Birthdate = DateTime.Now.AddDays(-800), .IsWorking = False}, _
	  New Person() With {.ID = 2, .Name = "Joe", .Birthdate = DateTime.Now.AddDays(-700), .IsWorking = True}, _
	  New Person() With {.ID = 3, .Name = "Joe", .Birthdate = DateTime.Now.AddDays(-600), .IsWorking = False}, _
	  New Person() With {.ID = 4, .Name = "Joe", .Birthdate = DateTime.Now.AddDays(-500), .IsWorking = True}, _
	  New Person() With {.ID = 5, .Name = "Joe", .Birthdate = DateTime.Now.AddDays(-400), .IsWorking = False}, _
	  New Person() With {.ID = 6, .Name = "Joe", .Birthdate = DateTime.Now.AddDays(-300), .IsWorking = True}, _
	  New Person() With {.ID = 7, .Name = "Joe", .Birthdate = DateTime.Now.AddDays(-200), .IsWorking = False}, _
	  New Person() With {.ID = 8, .Name = "Joe", .Birthdate = DateTime.Now.AddDays(-100), .IsWorking = True}, _
	  New Person() With {.ID = 9, .Name = "Joe", .Birthdate = DateTime.Now.AddDays(0), .IsWorking = False} _
	 }

	Sub Main()
		Dim table As New DataTable
		table.Columns.AddRange({New DataColumn("ID", GetType(Integer)), New DataColumn("Name", GetType(String)), New DataColumn("Birthdate", GetType(DateTime)), New DataColumn("IsWorking", GetType(Boolean))})

		Console.WriteLine("Method 1 -")
		For i As Integer = 0 To people.Count - 1
			Dim [row] As DataRow = table.NewRow()
			[row]("ID") = people(i).ID
			[row]("Name") = people(i).Name
			[row]("Birthdate") = people(i).Birthdate
			[row]("IsWorking") = people(i).IsWorking
			table.Rows.Add([row])
		Next

		For Each [row] As DataRow In table.Rows
			Console.WriteLine("Added - {0}", String.Join(", ", Array.ConvertAll([row].ItemArray, Function(x) x.ToString())))
		Next
		Console.ReadLine()
	End Sub
End Module

Class Person
	Public Property ID() As Integer
	Public Property Name() As String
	Public Property Birthdate() As DateTime
	Public Property IsWorking() As Boolean
End Class

Open in new window

Which produces the following output -Capture.JPG
What is FoundRows?

-saige-
0
smithmrkAuthor Commented:
OK, I think you missed my question.

I have a DataTable that is populated with users and user info...I then have a search button and if they type in a name I want the datatable cleared out and I use the FoundRows array to then populate the datatable again.

So I put all the users in the table to begin with then do a search...then I want to clear out the datatable and ONLY put in the users found from the search...the problem occurs after I do the MyDataTable.clear then try to start adding in new rows again.

Mark
0
it_saigeDeveloperCommented:
So do you find the rows in the current table that match the criteria?  If so, how do you add them to the FoundRows array?

-saige-
0
Cloud Class® Course: Ruby Fundamentals

This course will introduce you to Ruby, as well as teach you about classes, methods, variables, data structures, loops, enumerable methods, and finishing touches.

smithmrkAuthor Commented:
Here is the FULL Code for what I'm doing:

        'Create a DataTable of ALL the Users that are setup:
        Dim CurrentMembershipUsers As MembershipUserCollection
        Dim MyDataTable As New DataTable()

        'Set the Data Colums:
        MyDataTable.Columns.Add(New DataColumn("UserName", GetType(String)))
        MyDataTable.Columns.Add(New DataColumn("ProfileName", GetType(String)))
        MyDataTable.Columns.Add(New DataColumn("FirstName", GetType(String)))
        MyDataTable.Columns.Add(New DataColumn("LastName", GetType(String)))
        MyDataTable.Columns.Add(New DataColumn("JobTitle", GetType(String)))
        MyDataTable.Columns.Add(New DataColumn("EMail", GetType(String)))

        'Reload the NEW List of Users:
        Dim Members As MembershipUser
        GV_CurrentUsers.Dispose()

        If ddl_Roles.SelectedIndex = 0 Or ddl_Roles.SelectedIndex = -1 Then
            CurrentMembershipUsers = Membership.GetAllUsers

            For Each Members In CurrentMembershipUsers
                Dim UserProfile As ProfileCommon = Profile.GetProfile(Members.UserName)
                'Get the list of users setup:
                If Members.IsApproved = True Then
                    'Start Adding Rows:
                    Dim MyDataRow As DataRow = MyDataTable.NewRow()
                    MyDataRow("UserName") = UserProfile.UserName
                    MyDataRow("FirstName") = UserProfile.FirstName
                    MyDataRow("LastName") = UserProfile.LastName
                    MyDataRow("ProfileName") = UserProfile.FirstName & " " & UserProfile.LastName
                    MyDataRow("JobTitle") = UserProfile.JobTitle & "<br />" & UserProfile.Department
                    MyDataRow("EMail") = Members.Email
                    MyDataTable.Rows.Add(MyDataRow)
                    MyDataRow = MyDataTable.NewRow()
                End If
            Next
        Else
            Dim RoleUsers() As String
            RoleUsers = Roles.GetUsersInRole(ddl_Roles.SelectedItem.Text)

            For iUsers As Int32 = 0 To RoleUsers.Length - 1
                Dim UserProfile As ProfileCommon = Profile.GetProfile(RoleUsers(iUsers))
                'Get the list of users setup:
                If Membership.GetUser(UserProfile.UserName).IsApproved = True Then
                    'Start Adding Rows:
                    Dim MyDataRow As DataRow = MyDataTable.NewRow()
                    MyDataRow("UserName") = UserProfile.UserName
                    MyDataRow("FirstName") = UserProfile.FirstName
                    MyDataRow("LastName") = UserProfile.LastName
                    MyDataRow("ProfileName") = UserProfile.FirstName & " " & UserProfile.LastName
                    MyDataRow("JobTitle") = UserProfile.JobTitle & "<br />" & UserProfile.Department
                    MyDataRow("EMail") = Membership.GetUser(UserProfile.UserName).Email
                    MyDataTable.Rows.Add(MyDataRow)
                    MyDataRow = MyDataTable.NewRow()
                End If
            Next
        End If

        'Load the Users:        
        MyDataTable.DefaultView.Sort = "LastName ASC"
        Dim FoundRows() As DataRow = MyDataTable.Select("ProfileName LIKE '%" & txt_SearchName.Text & "%'")
        If FoundRows.Length > 0 Then
           MyDataTable.Rows.Clear()
            'Add the NEW Rows from Query:
            For iCount As Int16 = 0 To FoundRows.GetUpperBound(0)
                Dim MyDataRow As DataRow = MyDataTable.NewRow()
                MyDataRow("UserName") = FoundRows(iCount)(0)
                MyDataRow("FirstName") = FoundRows(iCount)(2)
                MyDataRow("LastName") = FoundRows(iCount)(3)
                MyDataRow("ProfileName") = FoundRows(iCount)(1)
                MyDataRow("JobTitle") = FoundRows(iCount)(4)
                MyDataRow("EMail") = FoundRows(iCount)(5)
                MyDataTable.Rows.Add(MyDataRow)
                MyDataRow = MyDataTable.NewRow()
            Next
        End If

        GV_CurrentUsers.DataSource = MyDataTable
        GV_CurrentUsers.Dispose()
        GV_CurrentUsers.PageSize = 20

        GV_CurrentUsers.DataBind()
        MyDataTable.Dispose()
0
it_saigeDeveloperCommented:
The problem that you are dealing with is that DataRow's are reference objects that are "joined" to a table.  When you select the row from the table you need to either:

A. Clone them.
B. Disjoin them from their parent table.

The reason for this is because when you clear the table the reference for the row is no longer valid, it is removed (or disposed, for lack of a better term); e.g. -Capture.JPG
So here are the potential fixes:

Creating a clone -
Module Module1
	ReadOnly people As New List(Of Person) From _
	 { _
	  New Person() With {.ID = 0, .Name = "Joe", .Birthdate = DateTime.Now.AddDays(-900), .IsWorking = True}, _
	  New Person() With {.ID = 1, .Name = "Joe", .Birthdate = DateTime.Now.AddDays(-800), .IsWorking = False}, _
	  New Person() With {.ID = 2, .Name = "Joe", .Birthdate = DateTime.Now.AddDays(-700), .IsWorking = True}, _
	  New Person() With {.ID = 3, .Name = "Joe", .Birthdate = DateTime.Now.AddDays(-600), .IsWorking = False}, _
	  New Person() With {.ID = 4, .Name = "Joe", .Birthdate = DateTime.Now.AddDays(-500), .IsWorking = True}, _
	  New Person() With {.ID = 5, .Name = "Joe", .Birthdate = DateTime.Now.AddDays(-400), .IsWorking = False}, _
	  New Person() With {.ID = 6, .Name = "Joe", .Birthdate = DateTime.Now.AddDays(-300), .IsWorking = True}, _
	  New Person() With {.ID = 7, .Name = "Joe", .Birthdate = DateTime.Now.AddDays(-200), .IsWorking = False}, _
	  New Person() With {.ID = 8, .Name = "Joe", .Birthdate = DateTime.Now.AddDays(-100), .IsWorking = True}, _
	  New Person() With {.ID = 9, .Name = "Joe", .Birthdate = DateTime.Now.AddDays(0), .IsWorking = False} _
	 }

	Sub Main()
		Dim table As New DataTable
		table.Columns.AddRange({New DataColumn("ID", GetType(Integer)), New DataColumn("Name", GetType(String)), New DataColumn("Birthdate", GetType(DateTime)), New DataColumn("IsWorking", GetType(Boolean))})

		Console.WriteLine("Method 1 -")
		For i As Integer = 0 To people.Count - 1
			Dim [row] As DataRow = table.NewRow()
			[row]("ID") = people(i).ID
			[row]("Name") = people(i).Name
			[row]("Birthdate") = people(i).Birthdate
			[row]("IsWorking") = people(i).IsWorking
			table.Rows.Add([row])
		Next

		For Each [row] As DataRow In table.Rows
			Console.WriteLine("Added - {0}", String.Join(", ", Array.ConvertAll([row].ItemArray, Function(x) x.ToString())))
		Next

		Dim found = (From [row] As DataRow In table.Rows Let [orphan] = [row].ItemArray.Clone() Where [row]("ID") Mod 3 = 0 Select [orphan]).ToArray()
		table.Rows.Clear()

		For i As Integer = 0 To found.Count - 1
			Dim [row] As DataRow = table.NewRow()
			[row]("ID") = found(i)(0)
			[row]("Name") = found(i)(1)
			[row]("Birthdate") = found(i)(2)
			[row]("IsWorking") = found(i)(3)
			table.Rows.Add([row])
		Next

		For Each [row] As DataRow In table.Rows
			Console.WriteLine("Found and Re-Added - {0}", String.Join(", ", Array.ConvertAll([row].ItemArray, Function(x) x.ToString())))
		Next
		Console.ReadLine()
	End Sub
End Module

Class Person
	Public Property ID() As Integer
	Public Property Name() As String
	Public Property Birthdate() As DateTime
	Public Property IsWorking() As Boolean
End Class

Open in new window


Disjoining from parent -
Module Module1
	ReadOnly people As New List(Of Person) From _
	 { _
	  New Person() With {.ID = 0, .Name = "Joe", .Birthdate = DateTime.Now.AddDays(-900), .IsWorking = True}, _
	  New Person() With {.ID = 1, .Name = "Joe", .Birthdate = DateTime.Now.AddDays(-800), .IsWorking = False}, _
	  New Person() With {.ID = 2, .Name = "Joe", .Birthdate = DateTime.Now.AddDays(-700), .IsWorking = True}, _
	  New Person() With {.ID = 3, .Name = "Joe", .Birthdate = DateTime.Now.AddDays(-600), .IsWorking = False}, _
	  New Person() With {.ID = 4, .Name = "Joe", .Birthdate = DateTime.Now.AddDays(-500), .IsWorking = True}, _
	  New Person() With {.ID = 5, .Name = "Joe", .Birthdate = DateTime.Now.AddDays(-400), .IsWorking = False}, _
	  New Person() With {.ID = 6, .Name = "Joe", .Birthdate = DateTime.Now.AddDays(-300), .IsWorking = True}, _
	  New Person() With {.ID = 7, .Name = "Joe", .Birthdate = DateTime.Now.AddDays(-200), .IsWorking = False}, _
	  New Person() With {.ID = 8, .Name = "Joe", .Birthdate = DateTime.Now.AddDays(-100), .IsWorking = True}, _
	  New Person() With {.ID = 9, .Name = "Joe", .Birthdate = DateTime.Now.AddDays(0), .IsWorking = False} _
	 }

	Sub Main()
		Dim table As New DataTable
		table.Columns.AddRange({New DataColumn("ID", GetType(Integer)), New DataColumn("Name", GetType(String)), New DataColumn("Birthdate", GetType(DateTime)), New DataColumn("IsWorking", GetType(Boolean))})

		Console.WriteLine("Method 1 -")
		For i As Integer = 0 To people.Count - 1
			Dim [row] As DataRow = table.NewRow()
			[row]("ID") = people(i).ID
			[row]("Name") = people(i).Name
			[row]("Birthdate") = people(i).Birthdate
			[row]("IsWorking") = people(i).IsWorking
			table.Rows.Add([row])
		Next

		For Each [row] As DataRow In table.Rows
			Console.WriteLine("Added - {0}", String.Join(", ", Array.ConvertAll([row].ItemArray, Function(x) x.ToString())))
		Next

		Dim found = table.Clone
		For Each [orphan] In (From [row] As DataRow In table.Rows Where [row]("ID") Mod 3 = 0 Select [row])
			found.ImportRow([orphan])
		Next
		table.Rows.Clear()

		For Each [orphan] In found.Rows
			table.ImportRow([orphan])
		Next

		For Each [row] As DataRow In table.Rows
			Console.WriteLine("Found and Re-Added - {0}", String.Join(", ", Array.ConvertAll([row].ItemArray, Function(x) x.ToString())))
		Next
		Console.ReadLine()
	End Sub
End Module

Class Person
	Public Property ID() As Integer
	Public Property Name() As String
	Public Property Birthdate() As DateTime
	Public Property IsWorking() As Boolean
End Class

Open in new window


Each of which produce the following output -Capture.JPG-saige-
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
smithmrkAuthor Commented:
OK, thanks!

Mark
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Visual Basic.NET

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.