Adding new data rows to a table is a three-step process:
1. Create a new row object.
2. Store the actual data values in the row object.
3. Add the row object to the table.
Creating New Rows
The DataColumn objects you add to a DataTable let you define an unlimited number of column combinations. One table might manage information on individuals, with textual name fields and dates for birthdays and driver-license expirations. Another table might exist to track the score in a baseball game, and contain no names or dates at all. The type of information you store in a table depends on the columns included in that table, along with the name, data type, and field constraints for each column.
Defining Row Values
The DataRow class includes an Item property that provides access to each defined column, by name, zero-based index number, or reference to the physical DataColumn instance. When writing code with a specific table format in mind, programmers generally use the columnname method because it makes clear which field is being referenced in a code statement.
C# oneRow.Item["ID"] = 123; // by column name
oneRow.Item[0] = 123; // by column position
DataColumn whichColumn = someTable.Columns[0];
oneRow.Item[whichColumn] = 123; // by column instance Visual Basic oneRow.Item("ID") = 123 ' by column name oneRow.Item(0) = 123 ' by column position
Dim whichColumn As DataColumn = someTable.Columns(0) oneRow.Item(whichColumn) = 123 '
by column instance
1:Open the “Chapter 3 CSharp” project from the installed samples folder. The project includes two Windows.Forms classes: AccountManager and AccountDetail.
2. Open the source code view for the AccountManager form. Locate the AccountManager_ Load event handler. This routine creates a custom DataTable instance with five columns: ID (a read-only, auto-generated long integer), FullName (a required 30-character unique string), Active (a Boolean), AnnualFee (an optional decimal), and StartDate (an optional date).
3. Add the following statements just after the “Build some sample data rows” comment. These rows add new DataRow objects to the table using the Rows.Add alternative syntax:
CustomerAccounts.Rows.Add(new Object[] {1L, "Blue Yonder Airlines", true, 500m, DateTime.Parse("1/1/2007")}); CustomerAccounts.Rows.Add(new Object[] {2L, "Fourth Coffee", true, 350m, DateTime.Parse("7/25/2009")}); CustomerAccounts.Rows.Add(new Object[] {3L, "Wingtip Toys", false});