Question Insert a record by using code in DataTable

roninkaiser

New member
Joined
Jun 14, 2012
Messages
3
Programming Experience
5-10
Hi all

I have a Textbox in which project I created a Dataset.
In the Dataset I created a Datatable containing 20 fields/columns.
How can I insert a record by using code in datatable?

Thank you
redface.gif
 
Last edited by a moderator:
I have translated the question into English from what appeared to be Italian. This is an English-speaking forum and I'm afraid that we require all posts to be in English.

Just to confirm, you are saying that you want to take the data from some TextBoxes and add them into a new row in a DataTable, correct?
 
Sorry for the question in italian......

I have a dataset (DatasetTest) in my project with a datatable(DataTable1).
The datatable has 30 columns(col1,col2,col3....).

If is possible, i want (by code) add new rows in the datatable. How?

Thanks
 
The DataTable has a Rows property, which is a collection of DataRows. It has an Add method, which will accept all the individual field values and then return the new DataRow that was added. Alternatively, you can call the NewRow method of the DataTable to create the DataRow, then set its fields by index or column name, then call a different overload of Rows.Add and pass the DataRow.
 
The code below will do what you want:


Dimension dTable as DataTable = New DataTable ("Employees")
dTable.Columns.Add("EmplID", System.Type.GetType("System.Int32"))
dTable.Columns.Add("FirstName", System.Type.GetType("System.String"))
dTable.Columns.Add("LastName", System.Type.GetType("System.String"))
dTable.Columns.Add("BirthDay", GetType(DateTime))
dTable.Columns.Add("BirthState", System.Type.GetType("System.String"))
dTable.Columns.Add("Sex", System.Type.GetType("System.Boolean"))
dTable.Columns.Add("Rank", System.Type.GetType("System.Int32"))
dTable.Columns.Add("AgeToday", System.Type.GetType("System.Int32"))

'Fill in DataTable from Array of Employees
For Each e As Employee In FillIn_Employees()
Dim r As DataRow = dTable.NewRow
r("EmplID") = e.IdNumber
r("FirstName") = e.FirstName
r("LastName") = e.LastName
r("BirthDay") = e.BirthDay
r("BirthState") = [Enum].GetName(GetType(States), e.BirthState)
r("Sex") = e.Sex
r("Rank") = e.Rank
r("AgeToday") = 32 'Now.Subtract(e.BirthDay)
dTable.Rows.Add(r)
Next
 
Back
Top