Adding a new row to datatable with vb.net
Tuesday 18 May 2010
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:
-
Dim MyConnection As SqlConnection
-
MyConnection = New SqlConnection()
-
MyConnection.ConnectionString = ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString
-
-
Dim sql As String = "SELECT id, name FROM [TABLE]"
-
-
Dim resultsDataTable As New DataTable()
-
Dim myDataAdapter As SqlDataAdapter = New SqlDataAdapter(sql, MyConnection)
-
myDataAdapter.Fill(resultsDataTable)
-
-
rpt.DataSource = resultsDataTable
-
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:
-
Dim dtNewRow As DataRow
-
dtNewRow = resultsDataTable.NewRow()
-
dtNewRow.Item("id") = 0
-
dtNewRow.Item("name") = "Joe Blogs"
-
resultsDataTable.Rows.Add(dtNewRow)
-
-
-
Dim v As DataView = resultsDataTable.DefaultView
-
v.Sort = "name DESC"
-
resultsDataTable = v.ToTable()
So the full section of code should look like this:
- Dim MyConnection As SqlConnection
- MyConnection = New SqlConnection()
- MyConnection.ConnectionString = ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString
-
- Dim sql As String = "SELECT id, name FROM [TABLE]"
-
- Dim resultsDataTable As New DataTable()
- Dim myDataAdapter As SqlDataAdapter = New SqlDataAdapter(sql, MyConnection)
- myDataAdapter.Fill(resultsDataTable)
-
-
- Dim dtNewRow As DataRow
- dtNewRow = resultsDataTable.NewRow()
- dtNewRow.Item("id") = 0
- dtNewRow.Item("name") = "Joe Blogs"
- resultsDataTable.Rows.Add(dtNewRow)
-
-
- Dim v As DataView = resultsDataTable.DefaultView
- v.Sort = "name DESC"
- resultsDataTable = v.ToTable()
-
- rpt.DataSource = resultsDataTable
- rpt.DataBind()
|
(11)
|
|
|