Updating record from DetailsView with Code-Behind
am 26.07.2007 13:30:03 von Stupid1I want to update my records in my DetailsView control using code-behind,
vb.net, however I keep running into road blocks. I am having a hard time
posting the data back to the db.
My app is pull all recs from the Employees table of the NW DB into a
GridView control. I have a asp:HyperLink control in the last column, Edit,
that passes the Key value of the row to the DetailsView on my Details.aspx
page. I then want the user to be able to make what ever changes they want,
and save the record back to the db.
It is the posting back to the db that I cannot get correct. Any help is
appreciated. Below is the code that I have for the ItemUpdating method:
Protected Sub dvDetails_ItemUpdating(ByVal sender As Object, ByVal e As
DetailsViewUpdateEventArgs) Handles dvDetails.ItemUpdating
Dim connStr As String =
ConfigurationManager.ConnectionStrings("NWConnectionString") .ToString()
Dim conn As New SqlConnection(connStr)
'Dim strSql As String = "SELECT * FROM Employees WHERE
EmployeeID=@EmployeeID"
Dim upSql As String = "UPDATE Employees SET LastName=@LastName,
FirstName=@FirstName, Title=@Title, Address=@Address," & _
"City=@City, Region=@Region, PostalCode=@PostalCode,
HireDate=@HireDate WHERE EmployeeID=@EmployeeID"
Dim da As New SqlDataAdapter
Dim ds As New DataSet
Dim ds1 As New DataSet
Dim upCmd As New SqlCommand(upSql, conn)
Dim idParam As SqlParameter = upCmd.Parameters.Add("@EmployeeID",
SqlDbType.Int, 4, "EmployeeID")
Try
' da.SelectCommand = New SqlCommand(strSql, conn)
'da.Fill(ds, "Employees")
upCmd.Parameters.Add("@LastName", SqlDbType.VarChar, 20,
"LastName")
upCmd.Parameters.Add("@FirstName", SqlDbType.VarChar, 10,
"FirstName")
upCmd.Parameters.Add("@Title", SqlDbType.VarChar, 30, "Title")
upCmd.Parameters.Add("@Address", SqlDbType.VarChar, 60, "Address")
upCmd.Parameters.Add("@City", SqlDbType.VarChar, 15, "City")
upCmd.Parameters.Add("@Region", SqlDbType.VarChar, 15, "Region")
upCmd.Parameters.Add("@PostalCode", SqlDbType.VarChar, 10,
"PostalCode")
upCmd.Parameters.Add("@HireDate", SqlDbType.DateTime, 8,
"HireDate")
idParam.SourceVersion = DataRowVersion.Original
conn.Open()
'Update Employees Table
ds1 = ds.GetChanges(DataRowState.Modified)
da.Update(ds1)
ds.Merge(ds1, False, MissingSchemaAction.Add)
ds.AcceptChanges()
dvDetails.DataBind()
Catch ex As Exception
'Display Error
Console.WriteLine("Error: " & ex.ToString())
Finally
'Close Connection
conn.Close()
'Redirect to Home
Response.Redirect("~/Default.aspx")
End Try
End Sub