Now that there is a table with columns and keys, some data can be added. The following code adds ten rows to the newly created Customers table.
[VB] Dim iCounter as integer Dim workRow as DataRow For i = 0 to 9 workRow = worktable.NewRow() workRow("CustID") = iCounter workRow("CustomerNameLast") = "CustName" & i.ToString() worktable.Rows.Add(workRow) Next [C#] DataRow workRow = null; for (int i = 0; i <= 9; i++) { workRow = workTable.NewRow(); workRow[0] = i; workRow[1] = "CustName" + i.ToString(); workTable.Rows.Add(workRow); }
In the code above, we declare a new variable as type DataRow. A new DataRow object is returned when the NewRow method is invoked. The DataTable builds the DataRow object based on the structure of the table (as defined by the ColumnsCollection).
[VB] Dim workRow As DataRow workRow = workTable.NewRow() [C#] Data.DataRow workRow; workRow = workTable.NewRow();
We then work with the newly built row either through an index or the column's name. Both of the following lines of code are valid:
[VB] workRow("CustID") = "CustName" & i workRow(1) = "CustName" & i [C#] workRow["CustID"] = "CustName" + i.ToString(); workRow[1] = "CustName" + i.ToString();
Once a row is populated with values, it is added into the table's RowsCollection using the Add method.
[VB] workTable.Rows.Add(workRow) [C#] workTable.Rows.Add(workRow);
In addition to adding rows this way, we can also add a new row my passing in an array of values (typed as object) using the Add method.
[VB] workTable.Rows.Add(new Object() {1, "CustName1"}) [C#] workTable.Rows.Add(new Object[] {1, "CustName1"});
This option simply creates a new row inside the table and sets its column values to the values in the object array. Note that the values in the array are matched sequentially to the columns in the table.