將資料加入至 DataTableAdding Data to a DataTable

建立 DataTable 並使用資料行和條件約束定義其結構之後,即可將新資料列加入資料表。After you create a DataTable and define its structure using columns and constraints, you can add new rows of data to the table. 若要加入新資料列,請將新變數宣告為 DataRow 型別。To add a new row, declare a new variable as type DataRow. 當您呼叫NewRow方法時,會傳回新的 DataRow 物件。A new DataRow object is returned when you call the NewRow method. 然後, DataTable會根據資料表的結構建立DataRow物件,如所DataColumnCollection定義。The DataTable then creates the DataRow object based on the structure of the table, as defined by the DataColumnCollection.

下列範例示範如何藉由呼叫NewRow方法來建立新的資料列。The following example demonstrates how to create a new row by calling the NewRow method.

Dim workRow As DataRow = workTable.NewRow()  
DataRow workRow = workTable.NewRow();  

接下來您可以使用索引或資料行名稱來管理新加入的資料列,如下列範例所示。You then can manipulate the newly added row using an index or the column name, as shown in the following example.

workRow("CustLName") = "Smith"  
workRow(1) = "Smith"  
workRow["CustLName"] = "Smith";  
workRow[1] = "Smith";  

將資料插入新的資料列之後,就會使用add方法將資料列加入至DataRowCollection,如下列程式碼所示。After data is inserted into the new row, the Add method is used to add the row to the DataRowCollection, shown in the following code.

workTable.Rows.Add(workRow)  
workTable.Rows.Add(workRow);  

您也可以呼叫add方法來加入新的資料列,方法是傳入值的陣列(類型為Object),如下列範例所示。You can also call the Add method to add a new row by passing in an array of values, typed as Object, as shown in the following example.

workTable.Rows.Add(new Object() {1, "Smith"})  
workTable.Rows.Add(new Object[] {1, "Smith"});  

將值陣列(類型為Object)傳遞至Add方法會在資料表內建立新資料列,並將其資料行值設定為物件陣列中的值。Passing an array of values, typed as Object, to the Add method creates a new row inside the table and sets its column values to the values in the object array. 請注意,陣列值將根據其在資料表出現的順序,依序和資料行相符。Note that values in the array are matched sequentially to the columns, based on the order in which they appear in the table.

下列範例會在新建立的Customers資料表中加入10個數據列。The following example adds 10 rows to the newly created Customers table.

Dim workRow As DataRow  
Dim i As Integer  
  
For i = 0 To 9  
  workRow = workTable.NewRow()  
  workRow(0) = i  
  workRow(1) = "CustName" & I.ToString()  
  workTable.Rows.Add(workRow)  
Next  
DataRow workRow;  
  
for (int i = 0; i <= 9; i++)   
{  
  workRow = workTable.NewRow();  
  workRow[0] = i;  
  workRow[1] = "CustName" + i.ToString();  
  workTable.Rows.Add(workRow);  
}  

另請參閱See also