We would like to update data in a SQL Server 2012 database with a value obtained from
changing a value on an ASP.Net DetailsView. I Would would like to update the database using
- a strongly typed DataSet called
DataSetParentsDetails - a TableAdapter called
ParentsDetailsTableAdapter - a DataTable called
ParentsDetails.
These were created with the DataSet Designer.
This is the code from the code-behind file used to figure out the amount we want to update into the database:
Protected Sub DetailsViewDetails_ItemCommand(sender As Object, e As System.Web.UI.WebControls.DetailsViewCommandEventArgs)
Dim dcmAmountToAdjust As Decimal
Dim StrSqlStatement As String
Select Case e.CommandName
Case "Add"
Case "Edit"
dcmOriginalRegistrationFee = GetValueFromLabelRegistrationFee()
Case "Delete"
Case "Update"
dcmNewRegistrationFee = GetValueFromTextBoxRegistrationFee()
dcmAmountToAdjust = dcmNewRegistrationFee - dcmOriginalRegistrationFee
' Update the tuition balance in the parent's data.
'-------------------------------------------------
StrSqlStatement =
"Update Students " & _
"Set RegistrationCode = RegistrationCode + @AmountToAdjust " & _
"Where StudentID = @ID"
' Code to update the database goes here.
'---------------------------------------
End Select
End Sub
I’m sure that this was asked many times before but I can’t find a good example on how to use the query in: StrSqlStatement to update the database through the strongly typed DataSet.
First off you need a connection string, it’s good practise to store your connection strings in the
web.configfile:This is a direct child of the root
<configuration>element. For more information about connection strings, visit http://www.connectionstrings.com.Then you’ll need some imports in your code-behind, and you’ll need to add them as references to your project if you haven’t already got them in there:
Then we connect to the database and run our command, we use parameters because they’re more secure.
Note that there is no need to use
conn.Close()here as theUsingstatement will take care of that for you (SqlConnection’s Dispose method closes the connection if it is still open).