11

I have a datatable with one column:

this.callsTable.Columns.Add("Call", typeof(String));

I then want to add a row to that datatable, but want to give a specific index, the commented number is the desired index:

this.callsTable.Rows.Add("Legs"); //11

Update:

  • Must be able to handle inputting hundreds of rows with unique indexes.
  • The index must be what is defined by me no matter if there are enough rows in the table or not for the insertat function.
RSM
  • 14,540
  • 34
  • 97
  • 144

1 Answers1

28

You can use DataTable.Rows.InsertAt method.

DataRow dr = callsTable.NewRow(); //Create New Row
dr["Call"] = "Legs";              // Set Column Value
callsTable.Rows.InsertAt(dr, 11); // InsertAt specified position

See: DataRowCollection.InsertAt Method

If the value specified for the pos parameter is greater than the number of rows in the collection, the new row is added to the end.

Habib
  • 219,104
  • 29
  • 407
  • 436
  • What If i want to define certain indexes for several hundred rows? I dont want to have to do all that for each row as well as define a different Datarow variable each time which would also have to have a new name everytime. Also, I want the index to be what I choose no matter if there are enough rows in the table or not. – RSM Dec 17 '13 at 14:43
  • 2
    @RyanMurphy, `InsertAt` only accepts a `DataRow` as parameter, so you have to use that. but you can reuse the variable `dr` in your iteration. – Habib Dec 17 '13 at 14:46
  • Say I have: DataRow dr = callsTable.NewRow(); dr["Call"] = "Legs"; callsTable.Rows.InsertAt(dr, 11); dr["Call"] = "Arms"; callsTable.Rows.InsertAt(dr, 9); It says this row is already in the datatable. – RSM Dec 17 '13 at 14:54
  • 2
    @RyanMurphy, you need to do `dr = dt.NewRow();` before using the `dr` again. – Habib Dec 17 '13 at 14:58
  • @Habib because of some conditions sometimes I only return fields (columns) without data so for that DT.NewRow() throws an exception of object reference. – Thrainder Aug 24 '21 at 10:36