Adding a new row to datatable with

Adding a new row to datatable with
If you want to manually add a row to a datatable that is already bound and to be able to reorder it, then this is how to do it.
For this example we will assume you are binding a datatable to a repeater, datagrid etc using code simular to below:
  1. Dim MyConnection As SqlConnection   
  2. MyConnection = New SqlConnection()   
  3. MyConnection.ConnectionString = ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString   
  5. Dim sql As String = "SELECT id, name FROM [TABLE]"  
  7. Dim resultsDataTable As New DataTable()   
  8. Dim myDataAdapter As SqlDataAdapter = New SqlDataAdapter(sql, MyConnection)   
  9. myDataAdapter.Fill(resultsDataTable)   
  11. rpt.DataSource = resultsDataTable   
  12. rpt.DataBind()  
Now we want to manually add a record with an ID of 0 and name of Joe Bloggs, so we do the below and insert it above the last two lines:
  1. Dim dtNewRow As DataRow   
  2. dtNewRow = resultsDataTable.NewRow()   
  3. dtNewRow.Item("id") = 0   
  4. dtNewRow.Item("name") = "Joe Blogs"  
  5. resultsDataTable.Rows.Add(dtNewRow)   
  7. 'This part allows you to sort your results   
  8. Dim v As DataView = resultsDataTable.DefaultView   
  9. v.Sort = "name DESC"  
  10. resultsDataTable = v.ToTable()  
So the full section of code should look like this:

32 people like this article, click here to say you like this article too (32)
Send a link to this page via email Send a link to this page