vb asp.net session variable not working? - asp.net

I just want to control which button user clicked, so I use Session Variable to store that data because I have to create all dynamic control in the Page_Load (to allow event handler work properly). The problem is this Session Variable is not work at the first time I clicked but only the second time.
Here is my code:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not Page.IsPostBack Then
'For the first time I want this session variable to be false because Image Button is not yet click
Me.Session("ImageClick") = False
End If
If Me.Session("ImageClick") Then
'Then after Button Image is clicked I try to add Dynamic control to a div
AddPreviewTable(0)
CreateButtomButton(Me.Session("totalPage"))
Debug.WriteLine(Me.Session("totalPage"))
Me.Session("ImageClick") = False
End If
End sub
The problem is I have to click on ButtonImage two times to turn Me.Session("ImageClick") to True.

Your if block is incorrect. You need to cast your session object into a bool:
If (Session("ImageClick") Is Not Nothing And CBool(Me.Session("ImageClick"))) Then
'Do your stuff.
End If

Related

Setting button invisible with event not working

I have a Visual Basic Project where I have a page(Parent.aspx) with a user control inside(ChildForm.ascx), the user control have a checkboxlist where if the selection is changed I cause a postback and send an event
Protected Sub checkBoxList_checked(ByVal sender As Object, ByVal e As EventArgs) Handles checkBoxList.SelectedIndexChanged
RaiseEvent MyEvent(sender, e)
End Sub
to make a button invisible on the Parent view
Protected Sub ChildForm_MyEvent(ByVal sender As Object, ByVal e As EventArgs) Handles ChildForm.MyEvent
If condition Then
btnSave.Visible = False
Else
btnSave.Visible= True
End If
End Sub
When I debug I see the breakpoint hitting all the lines of code and the condition apply as intended, but the button is not hidden, I dont know why if is setting the correct value it never refreshes the Parent page to show the changes, even if it does cause a postback.
Please help
Check your page load events (load, prerender, prerenderComplete) to make sure you are not setting the visibility property in there. if you are, you may need to use
"If not IsPostBack"

Why can't I access Session values from Page_Init that were stored during a previous postback?

I'm storing Session values inside of Page_Load during postback, but I'm unable to access them in Page_Init on the next round trip. The gist of my logic is that the end user should be able to log in on postback during Page_Load where values are stored in the Session object, then on the next round trip I can grab those values from the Session object and initialize objects of a custom type. Initially I attempted to initialize my objects based on the values stored in the Session, but when I found that wasn't working I added some code in Page_Init to debug and found that I wasn't able to access them at all. The catch is that I'm able to access the values fine if I completely reload the page - but if I try to refresh or try to fire the postback button again it's as though the code is ignored.
I'm able to access other values in the Session with this logic (I have a "StartTime" value I'm able to get that's created in BeginRequest) but I'm not able to access the ones created during postback in Page_Load.
This is independent of my custom type as I've tried with hardcoded values and arrived at the same result.
Where my postback is handled:
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
Select Case Me.form_action.Value.ToLower()
Case "save"
If Me.tab.ActiveTabIndex = 0 Then
cart.Login(Me.login.Value, Me.password.Value)
UpdateRecord()
End If
End Select
End Sub
These methods update the database and store the session value:
Public Sub UpdateRecord()
cart.UpdateDB()
SaveCart()
End Sub
Public Sub SaveCart()
If Not cart.ID > 0 Then Exit Sub
Me.cart_id.Value = cart.ID
Session("seminars_cart_id") = cart.ID
End Sub
This is where I attempt to access the data in Page_Init
Protected Sub Page_Init(sender As Object, e As EventArgs) Handles Me.Init
If Session.Keys.Count > 0 Then
phDbg.InnerHtml = ""
For Each k As Object In Session.Keys
Me.phDbg.InnerHtml += String.Format("Session({0}) - {1}<br />", k, Session(k))
Next
End If
End Sub

How To Pass Control As A Variable

This is one of those problems which seems like it should have a simple solution but I can't work out what it is!
How can I pass a control from one sub to another if the first sub doesn't actually call the second? For example, where btnChangeText is in a panel that has a ModalPopupExtender called mpExample, and therefore isn't usually visible:
Protected Sub btnChangeText_Click(sender as object, e as EventArgs) Handles btnChangeText.Click
<SpecifiedTextBox>.Text = "Hello"
End Sub
And then on the main page, visible at all times, is a button associated with each textbox. In this example, it's textbox15:
Protected Sub btnChangeTextBox15_Click(sender as object, e as EventArgs) Handles btnChangeTextBox15.Click
<Set TextBox15 as variable>
mpExample.Show()
End Sub
I know it's a silly example - believe me when I say that the real application I want to make of this actually makes sense! But the point is that I want to somehow store the name of the control to be updated by the first sub when the second sub is run.
If I was calling the first sub from the second it'd be easy, I'd just pass it as an argument, but I'm not. The first sub is called from a button click and is an independent action from the running of the second sub.
I don't seem to be able to use a session variable (my first thought) because I can't find any way to store the control name as a string and then convert it back to an actual control when the first sub runs. That'd be the easiest answer if somebody could tell me how to do it.
One approach would be to store the control's ID as a string in a Session variable, and then use the FindControl method to grab the control in your 2nd Click event.
Protected Sub btnChangeTextBox15_Click(sender as object, e as EventArgs) Handles btnChangeTextBox15.Click
Session("currentTextBox") = TextBox15.ID
mpExample.Show()
End Sub
Protected Sub btnChangeText_Click(sender as object, e as EventArgs) Handles btnChangeText.Click
Dim currentTextBox As TextBox
currentTextBox = CType(Page.FindControl(Session("currentTextBox")),TextBox)
currentTextBox.Text = "Hello"
End Sub
Note that if your TextBox15 control is inside some kind of container (a Panel or something), you'll need to use that container's FindControl method, rather than Page.FindControl.
Another approach is to store the TextBox itself in a Session variable, and then pull that out to set the text in your other method. Note that this only works if the methods are both called in the same request (which doesn't sound like it would work for your use-case). Here's what that would look like:
Protected Sub btnChangeTextBox15_Click(sender as object, e as EventArgs) Handles btnChangeTextBox15.Click
Session("currentTextBox") = TextBox15
mpExample.Show()
End Sub
Protected Sub btnChangeText_Click(sender as object, e as EventArgs) Handles btnChangeText.Click
Dim currentTextBox As TextBox
currentTextBox = CType(Session("currentTextBox"), TextBox)
currentTextBox.Text = "Hello"
End Sub

session variable set by checkbox not being stored/shared from page to page

I have a listview that's showing a long list. Each item has the ability to be 'hidden' or not. I want a checkbox to either show all the list, or not to show the hidden ones. The idea is that users will hide the older items they don't want to see any more, but may want to see at some point. I want to store the value of this decision in a session variable so if the user navigates to another page, then comes back, the ShowAllCheckbox will pre-populate to what the user has previously decided. Everything is working good, except i can't get the session variable to keep. It keeps going back to False. This is what I have:
aspx page:
Show Hidden: <asp:Checkbox ID="ShowHiddenCheckbox" runat="server" AutoPostBack="True" OnCheckedChanged="ShowHiddenCheckboxChange" />
...
<asp:ListView ...>
<!-- this list works fine, and pulls the correct records -->
aspx.vb page:
Protected Sub ShowHiddenCheckBoxChange(ByVal sender As Object, ByVal e As EventArgs)
' toggle the values
Dim CheckBoxField As CheckBox = TryCast(sender, CheckBox)
If CheckBoxField.Checked Then
Session("ShowHiddenRotations") = False
Else
Session("ShowHiddenRotations") = True
End If
End Sub
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
'if i navigate to another page, and come back to this one, this comes back as "False". I don't understand how it could be reset to False.
Response.Write( "Session: " & Session("ShowHiddenRotations") )
'when page loads check if session variable has been set to show/hide the hidden rotations
If Session("ShowHiddenRotations") Then
If Session("ShowHiddenRotations") = True Then
'update sql query on select statement to show the hidden rotations
'update checkbox to show it as checked
ShowHiddenCheckBox.Checked = True
Else
ShowHiddenCheckBox.Checked = False
End If
Else
'not checked by default (ie don't show hidden)
ShowHiddenCheckBox.Checked = False
End If
End Sub
The Session variable always reverts back to False when i navigate to another page and come back to this one. My understanding of session variables was that they would pass their values from one page to another until the user closes the browser. Maybe there's another way of doing this, or something simple I'm missing. Any help is much appreciated! Thanks!
Is session-state enabled on your site? It can be disabled in a couple of different way, on a page level or even in web.config.
You should also be aware the Page_Load event fires for every request, before the check-box auto-postback happens.
I'm also a little confused as to what you're trying to store: I assume every row has a check-box, but it seems you're trying to store the set/not-set value in a single session variable. How do you differentiate which have been selected, and which ones hasn't? :)
Update:
Okay, let's try a clean the code up a little bit. First create a property to access the session value:
Private Property ShowHiddenRotations As Boolean
Get
If Not Session("ShowHiddenRotations") Is Nothing Then
Return CType(Session("ShowHiddenRotations"), Boolean)
Else
Return False
End If
End Get
Set(value As Boolean)
Session("ShowHiddenRotations") = value
End Set
End Property
If you're using that value on other pages, I would recommend moving it to a seperate class.
Then we can reduce your other code to something closer to this:
Protected Sub ShowHiddenCheckBoxChange(ByVal sender As Object, ByVal e As EventArgs)
ShowHiddenRotations = ShowHiddenCheckbox.Checked
End Sub
And ...
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If not Page.IsPostBack
' Load your data, better stick it in a seperate sub...
ShowHiddenCheckBox.Checked = ShowHiddenRotations
else
' This section is executed BEFORE any control methods are run, i.e. ShowHiddenCheckBoxChange
end if
End Sub
I'm guessing your problem is really just the order of how things are called in your page. What happens when you debug through it?

client side script for treeview events

I have a Treeview with "populateOnDemand" set to true. I want this treeview to keep its state (nodes expanded/collapsed) from one page to another. Viewstate doesn't work because the treeview is different for each page. Here is my code at the moment.
ASPX page :
<asp:TreeView
ID="arbre"
EnableViewState="true"
PopulateNodesFromClient="true"
runat="server" />
Code behind :
Protected Sub arbre_TreeNodeCollapsed(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.TreeNodeEventArgs) Handles arbre.TreeNodeCollapsed
CType(Session("listeNoeudsOuverts"), Hashtable)(e.Node.Value) = True
End Sub
Protected Sub arbre_TreeNodeExpanded(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.TreeNodeEventArgs) Handles arbre.TreeNodeExpanded
CType(Session("listeNoeudsOuverts"), Hashtable)(e.Node.Value) = False
End Sub
Protected Sub arbre_TreeNodePopulate(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.TreeNodeEventArgs) Handles arbre.TreeNodePopulate
// code to populate nodes
CType(Session("listeNoeudsOuverts"), Hashtable)(e.Node.Value) = True
End Sub
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Session("listeNoeudsOuverts") Is Nothing Then
Session("listeNoeudsOuverts") = New Hashtable()
End If
// other stuff
End Sub
This works well, buf I wish I could avoid the postback everytime the user expands or collapses a node. I know I can set EnebleClientScript to true and manage the events client side in Javascript but I won't be able to use my session variable anymore. Is there a way to achieve this ?
Thank you
I will answer myself to a certain extent.
I've done some tests and research, EnableClientScript is true by default, and indeed means that expand and collapse actions are processed client side, by Javascript code that is automaticalt generated by the .Net framework. You can't edit it.
Apparently, if you need to add custom actions when a user expands or collapses anode, you have to use TreeNodeExpanded and TreeNodeCollapsed events, like i did above, and can't avoid postbacks because they are triggered server-side.

Resources