?
Solved

Scope problem: Class-based db Updating

Posted on 2005-05-04
4
Medium Priority
?
222 Views
Last Modified: 2010-04-07
An earlier question of my resulted in a model for updating a database:
http://www.experts-exchange.com/Programming/Programming_Languages/Dot_Net/ASP_DOT_NET/Q_21398677.html

Using that code I'm able to populate the form from the db (via class methods) but I can't quite see how to write the updates back. But it's not clear how the Update method is called by the submit button's click. Most of my confusion stems from the instantiation of the Addresses object for the original form population (get values from db; insert them 2 editable text fields) and why that has to be repeated (the object creation) to send the changes back to the Update method.

It seems to me that since the class is declared Public it should be avalible to all events (page_load & form submit) on the page. Ok...since the page_load Dims the object the scope is limited to that sub...but .... well....here's where i get stuck.

This is the vb snippet from the original question - I've added my specific questions with  ////:

Public Class Addresses
   Private sState As String ' these are used internally
   Private sCity As String
   Private iID As Integer
   
   
   Public Property State() As String ' these are publicly addressable from code
      Get
         Return sState
      End Get
      Set
         sState = value
      End Set
   End Property
   
   Public Property City() As String
      Get
         Return sCity
      End Get
      Set
         sCity = value
      End Set
   End Property
   
   Public Property ID() As Integer
      Get
         Return iID
      End Get
      Set
         iID = value
      End Set
   End Property
   
   
   Public Sub LoadValues()
      ' this loads the values based what you're looking for
      Dim conn As New SqlConnection(System.Configuration.ConfigurationSettings.AppSettings("connCommon"))
      Dim cmd As New SqlCommand()
      cmd.Connection = conn
      cmd.CommandText = "sp_GetAddress"
      cmd.CommandType = CommandType.StoredProcedure
      cmd.Parameters.Add("@id", iID)
      conn.Open()
      Dim dr As SqlDataReader = cmd.ExecuteReader()
     
      dr.Read()
      If dr.HasRows Then
         sCity = dr("city").ToString()
         sState = dr("state").ToString()
      End If
      cmd.Connection.Close()
      cmd.Dispose()
      conn.Close()
   End Sub 'LoadValues
   
   Public Sub Update()
      Dim conn As New SqlConnection(System.Configuration.ConfigurationSettings.AppSettings("connCommon"))
      Dim cmd As New SqlCommand()
      cmd.Connection = conn
      cmd.CommandText = "sp_SaveAddress"
      cmd.CommandType = CommandType.StoredProcedure
      ' parameter from string
      cmd.Parameters.Add("@city", sCity)
      cmd.Parameters.Add("@state", sState)
      cmd.Parameters.Add("@id", iID)
     
      Dim pOut As New SqlParameter()
      pOut = cmd.Parameters.Add("@ID_Out", SqlDbType.Int)
      pOut.Direction = ParameterDirection.Output
     
      cmd.Connection.Open()
      Try
         cmd.ExecuteNonQuery()
      Catch se As SqlException
      End Try
      ' do whatever you want here
      cmd.Connection.Close()
      cmd.Dispose()
      conn.Close()
   End Sub 'Update
End Class 'Addresses

 ' And then this is on your form.aspx.cs/vb page
'PRE-POPULATING THE FORM
////should be added to the page_load event, right?
Dim cAddress As New myNameSpace.Addresses()
cAddress.ID = 5 ' this is however you determine, your value
cAddress.LoadValues()
tbCity.Text = cAddress.City
tbState.Text = cAddress.State


////should be wrapped in the submit buttonclick event handler, right?
////
' SAVING THE FORM
Dim cAddress As New myNameSpace.Addresses()
cAddress.ID = 5 ' this is however you determine, your value
cAddress.LoadValues()
cAddress.City = tbCity.Text
cAddress.State = tbState.Text
cAddress.Update()

0
Comment
Question by:juststeve
  • 2
  • 2
4 Comments
 
LVL 23

Accepted Solution

by:
Jens Fiederer earned 1400 total points
ID: 13927204
The fact that the class is public simply means that its public methods are available in your code...it does not mean that the VALUES are stored between events on the server.  That is why you need to create a new Addresses in each of your event handlers that needs one.

It does NOT necessarily mean you have to get the values from the database again (unless your ID changes).  You could put

Session("addressdata") = cAddress

at the end of page_load (within a "if not page.ispostback" block along with the rest of that code, of course),
and replace the dim-LoadValues part of your code in the event handler with

Dim cAddress As myNameSpace.Addresses = Session("addressdata")

Key is:  web server does not store simple global variables between events unless you SPECIFICALLY save them in a session or application variable.  This makes sense, because consider:  2 different people could be using your page, one getting and editing ID=5 and the other maybe ID=6, and the server must store different cAddress values for each separate session in order to get this right.
0
 

Author Comment

by:juststeve
ID: 13927879
Ok...so if i have a click handler instantiating a new Address object then setting it's values according to textbox values it looks like I have to send that newly instantiated object to the Update method:

    Private Sub btnSubmit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSubmit.Click
        Dim myAddress As New RowEdit.Address
        '
        myAddress.City = tb_City.Text
        .
        .
        .
        myAddress.Update(myAddress)
    End Sub

This works for me so perhaps i shouldn't argue with sucess but...
0
 
LVL 23

Expert Comment

by:Jens Fiederer
ID: 13929196
You can do it either that way or the way I suggested (storing in a Session variable).  My suggestion uses less database access...your method gets the freshest version (probably not worth it in this particular case, since all the data is overwritten with textbox data anyway ... but if there were a field that was not displayed on the screen, and somebody else updated it between the time of the load and the update, your way preserves the most recent update).
0
 

Author Comment

by:juststeve
ID: 13929946
thankx!
0

Featured Post

Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

A quick way to get a menu to work on our website, is using the Menu control and assign it to a web.sitemap using SiteMapDataSource. Example of web.sitemap file: (CODE) Sample code to add to the page menu: (CODE) Running the application, we wi…
Introduction This article shows how to use the open source plupload control to upload multiple images. The images are resized on the client side before uploading and the upload is done in chunks. Background I had to provide a way for user…
Integration Management Part 2
Screencast - Getting to Know the Pipeline
Suggested Courses

840 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question