I have the following code to try to use viewstate to save a variable for postback. When post back occurs the SrString value is nothing. I have set the ViewState value at the dropdownlist index chane event and set the variable equal ot ViewState("SrString") at page in the if ispostback block.
Can anyone help?
Thanks
'Page Load
If IsPostBack Then
SrString = ViewState("SrString")
End If
'DropDownList Index change event
Protected Sub ByteDataFile_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs) Handles ByteDataFile.SelectedIndexChanged
ViewState("SrString") = SrString
End Sub
My web config file is correct, because I have other pages in the web site that works with the viewstate fine.
What am I missing?
That is because Page_Load is executed before ByteDataFile_SelectedIndexChanged.
ASP.NET Page life cycle always executes Page_Load first and then it handles events like clicks and SelectedIndexChanged, so when you say SrString = ViewState("SrString") in Page_Load, the ViewState("SrString") = SrString line hasn't been called yet.
http://msdn.microsoft.com/en-us/library/ms178472.aspx
Assuming you get the value for SrString from dropDownList's selected item, you just need to get that in Page_Load, something similar to this:
If IsPostBack Then
'I got this from your comment in the other answer, but I suppose LineNo and FileNameID are comming somehow from the drop downlist, right?
ViewState("SrString") = "\\...\soi\Bytewise\Line " & LineNo & "\Text Files\" & FileNameID
End If
Another thing you need to be sure is that the DropDownList has its AutoPostBack property set to true, otherwise the page won't postback when you change the selection.
For this kind of thing I think you should use a HiddenField instead of the ViewState.
http://wiki.asp.net/page.aspx/298/hiddenfield/
Where is SrString set? From the code you posted, it is only ever assigned to or from the ViewState, and therefore will always be null.
Some more explanation:
If IsPostBack Then
SrString = ViewState("SrString")
End If
'DropDownList Index change event
Protected Sub ByteDataFile_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs) Handles ByteDataFile.SelectedIndexChanged
ViewState("SrString") = SrString
End Sub
In page load, we set SrString to the value in the view state.
In your changed event, we set the ViewState to the value of SrString.
However, at no time is SrString ever set to a value, so you're just passing a null value around. There needs to be, somewhere:
SrString = 'some value from somewhere besides the viewstate.
Given:
a=b
b=a
And no other assignment, the value will never change.
Related
I have a page with GridView. The GridView has select button. Normally I use GridView's selected index changed event to do all kinds of operations when user clicks select button. But now I want to do some operations in Page_Load event based on grid view's selected row. Since the Selected_Index_changed event occurs after Page_Load how do I know following things in page load event.
I checked the asp lifecycle and this other question but I dont know how to do this.
How about using a QueryString to transmit which row was selected and then in the Page_Load event get the QueryString parameters? This is an example.
Protected Sub LinkButton1_Command(sender As Object, e As CommandEventArgs)
Dim UserId As Integer = e.CommandArgument 'Here goes whatever value you're trying to pass
Response.Redirect("~/OtherPage.aspx?UserId=" _
& UserId)
End Sub
This is in the OtherPage.aspx
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
UserId = Request.QueryString("UserId")
'Your code
end sub
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
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
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?
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim lab As Label = Me.GridView1.FindControl("Label1")
If TextBox2.Text = "7" Then
GridView1.SelectedRow.Cells(2).Text = "500"
Else
GridView1.SelectedRow.Cells(2).Text = "950"
End If
End Sub
The following error occurs : Object reference not set to an instance of an object.
You've got this code in your Page Load event, so it will run when the page is first loaded, and on every single postback. This probably isn't what you want.
I imagine that on the very first load, there isn't a selected row in your GridView, so GridView1.SelectedRow is going to be null. If this isn't null, then Cells or Cells(2) definitely will be. Trying to access a property on null is going to throw a NullReferenceException - "Object reference not set to an instance of an object".
As this MSDN example shows, you're probably better off accessing the SelectedRow property in an event handler for the SelectedIndexChanged event of the GridView.
Dim lab As Label = Me.GridView1.FindControl("Label1")
It doesn't look like you're doing anything with this label. Put a breakpoint on that line and see if it finds it. If it doesn't and you don't even use it, take the line out.
Also, check if textbox2 is valid whilst debugging.