Jimsan
Jimsan

Reputation: 305

ASP.Net - Using variable value in different button click events - VB

I have a multiview with 4 views. To switch between the views I use 4 buttons and switch the multiview's activeview index to the relevant view inside the click event of each button.

In each view there are various controls to capture data. There is then a submit button at the bottom of the final view to write all the data to a database.

What I want to achieve is to capture a time stamp of when the user clicks the button to move to each view (which will ultimately be written to the database). I can assign a timestamp to a variable by using the below code in the click event of each of the 4 buttons

Dim phase1TimeStamp as string = DateTime.Now.TimeOfDay.ToString()

The problem is, when I come to write the records to the database in the click event of the submit button, it cannot see the values assigned to these time stamp variables.

Is there a way I can pass these variable values to the submit button click event or is there a different way I can achieve this altogether? Thanks

Upvotes: 0

Views: 1371

Answers (2)

Karl Anderson
Karl Anderson

Reputation: 34834

You can store the values in Session cache, like this:

Session("MultiView1_Clicked_DateTime") = DateTime.Now.TimeOfDay.ToString()
Session("MultiView2_Clicked_DateTime") = DateTime.Now.TimeOfDay.ToString()
Session("MultiView3_Clicked_DateTime") = DateTime.Now.TimeOfDay.ToString()
Session("MultiView4_Clicked_DateTime") = DateTime.Now.TimeOfDay.ToString()

The Session value will exist in memory across page requests.

Note: You can name the Session key whatever you wish, but to get the value back out you need to match that key name exactly. Also, everything in Session is stored as an Object so you will need to cast the value to a String when you want to retrieve the value.

Upvotes: 1

Douglas Barbin
Douglas Barbin

Reputation: 3615

The easiest way to do this is probably by saving the variable to session, then retrieving it. You didn't say if this was ASP .NET Web Forms or MVC, so I will give you an option for each. MVC has a few different ways you can achieve this (ViewData, ViewBag, TempData, or directly to Session). I'm not quite as familiar with Web Forms but you can at least save to Session.

Web Forms

to save to session:

HttpContext.Current.Session("phase1TimeStamp") = phase1TimeStamp.ToString()

to retrieve it (you may have to cast it, depending on the type and your VB settings):

Dim myVar as String = HttpContext.Current.Session("phase1TimeStamp")

MVC

to save to session:

Session("phase1TimeStamp") = phase1TimeStamp.ToString()

to retrieve it:

Dim myVar as String = Session("phase1TimeStamp")

A note about MVC: If you want this to work across multiple sessions (I.E., for different users or even for the same user but with multiple tabs open), you will need to append the identifier ("phase1TimeStamp") in this case with some sort of unique identifier.

Upvotes: 2

Related Questions