Variable loses scope when used through button.click handler - asp.net

When I call my function at Me.Load everything is OK, but when I trigger my function only on the button click event all variables inside lose their set values. I just started on VB.NET so I don't fully understand scope nature here.
Here is my code:
Public Class WorkflowForward
Inherits FileBound.Web.FBBasePage
' Private decalrations
Private cfile_id As String = "" ' Current files ID
Private FBProject As Project = Nothing ' FileBound Project object
Private cmd As String = "" ' SQL query string
Private FBFile As FileBound.File = Nothing ' Filebound file holder
Private FBRoutes As RouteCollection = Nothing ' FileBound route collection holder
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
' Set SqlDataSource connection string
FBSqlDataSource.ConnectionString = ConfigurationManager.ConnectionStrings("FB_0371tcc").ConnectionString
If Not Me.IsPostBack Then
' Set values to variables
Page_setup() ' Here I set values to variabels
setRoute_debug("Admin1 Test")
End If
End Sub
Protected Sub sendEmail_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles sendEmail.Click
' CAN I HAZ SOME TEST????
'setRoute_debug(emailTo.SelectedValue.ToString)
Response.Write("<script>" & Me.FBRoutes.TotalCount.ToString & "</script>")
End Sub
Private Sub setRoute_debug(ByVal route_to As String)
' IF WE HAZ SOME ITEMS FINISH THEM MUHUHAHHAHAHA
If FBBusiness.LoggedInUser.RoutedItems.TotalCount > 0 Then
For Each item As RoutedItem In FBBusiness.LoggedInUser.RoutedItems
item.Complete("Completed!")
Next
End If
' DEBUG MODE #YOLO
' I'VE DONE IT I CAN HAZ ROUTEZ
For Each r As Route In Me.FBRoutes
If r.Name = route_to Then
For Each doc As FileBound.Document In FBFile.Documents
doc.Route(r.ID)
Next
End If
Next
End Sub
Private Sub Page_setup()
' Some code that sets values
End Sub
End Class
When I click the button it throws this error:
Object reference not set to an instance of an object.
Line 46: Response.Write("<script>" & Me.FBRoutes.TotalCount.ToString & "</script>")

A button click on as asp.net page would come as a PostBack.
Your are setting up the page only in
If Not Me.IsPostBack
This is fine for asp.net controls, cause they retain their state across PostBacks using the ViewState.
When click a button, server receives a new request, and a new object of Page is created. Your variables are not set for this object.
Set your page level variables on every PostBack, like this
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
' Set SqlDataSource connection string
FBSqlDataSource.ConnectionString = ConfigurationManager.ConnectionStrings("FB_0371tcc").ConnectionString
Page_setup() ' Here I set values to variables
If Not Me.IsPostBack Then
'Set Page level control values like TextBox values
End If
End Sub

Related

asp.net how do i transfer listbox values generated from a query to anoter listbox without a NullReferenceException error?

What i'm trying to do is to generate data on a ListBox from a query and then i can select some values, press a button and move those values to another ListBox.
When i try to move the values from a ListBox by the selecting the values and pressing the button i get the following error message:
System.NullReferenceException: 'Object reference not set to an instance of an object.' i think this is because im making a reference to the value and i'm not creating an instance of the value (correct me if i am wrong)
To fix this i believe i might have to instantiate each query value in an array to add to the listbox.
If this is correct what is the correct way to implement that array?
How i populate the ListBox
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
FillSitesListbox()
End Sub
Private Sub FillSitesListbox()
Try
dt = SQL.ExecQuery("SELECT s.Str_ID, s.Nm, d.str_grp_id, (Cast(s.Str_ID As varchar) + ' - ' + s.Nm + ' [ ' + Cast(d.str_grp_id As varchar) + ' ]' ) as IDDesc
FROM Retail_Store s left outer join store_group d on ( s.str_id = d.str_id )
ORDER BY s.Str_ID")
Catch ex As Exception
MsgBox(ex.Message)
Exit Sub
End Try
SitesListBox.DataTextField = "IDDesc"
SitesListBox.DataSource = dt
SitesListBox.DataBind()
End Sub
How i move values between ListBoxes
Protected Sub FromSiteButton_Click(sender As Object, e As EventArgs) Handles FromSiteButton.Click
SitesListBox.Items.Add(StoresListBox.SelectedItem)
SitesListBox.Items.Remove(SitesListBox.SelectedItem)
End Sub
Protected Sub FromStoreButton_Click(sender As Object, e As EventArgs) Handles FromSTOREButton.Click
StoresListBox.Items.Add(SitesListBox.SelectedItem)
StoresListBox.Items.Remove(SitesListBox.SelectedItem)
End Sub
How i execute a query
Public Function ExecQuery(query As String) As DataTable
Dim DBDT = New DataTable
Using DBCon As New SqlConnection(ConStr),
DBCmd As New SqlCommand(query, DBCon)
Params.ForEach(Sub(p) DBCmd.Parameters.Add(p))
Params.Clear()
DBCon.Open()
DBDT.Load(DBCmd.ExecuteReader)
End Using
Return DBDT
End Function
'Add Params
Public Sub AddParam(Name As String, Value As Object)
Dim NewParam As New SqlParameter(Name, Value)
Params.Add(NewParam)
End Sub
End Class
It seems that the code that moves the items is wrong.
In the first click (FromSiteButton_Click) you add the SelectedItem of the StoresListBox to the SiteListBox and then remove the SelectedItem from SitesListBox. I think you should add to the StoreListBox and remove from Sites selected item of that box. The same happens in the move FromStore
In any case, to avoid NRE you should always test if the reference variables that you are using are Nothing or not before using them
Protected Sub FromSiteButton_Click(sender As Object, e As EventArgs) Handles FromSiteButton.Click
If SitesListBox.SelectedItem IsNot Nothing Then
StoresListBox.Items.Add(SitesListBox.SelectedItem)
SitesListBox.Items.Remove(SitesListBox.SelectedItem)
End If
End Sub
Protected Sub FromStoreButton_Click(sender As Object, e As EventArgs) Handles FromSTOREButton.Click
If StoresListBox.SelectedItem IsNot Nothing Then
SitesListBox.Items.Add(StoresListBox.SelectedItem)
StoresListBox.Items.Remove(StoresListBox.SelectedItem)
End If
End Sub

Listbox.items.count is always 0?

I am trying to determine if a list box has any text in it. I tried using a custom validator and the code below always has a result of 0 or false either when there is text or no text in the list box? How can I properly determine if there is text in a list box?
Protected Sub CustomValidator1_ServerValidate(ByVal source As Object, ByVal args As System.Web.UI.WebControls.ServerValidateEventArgs) Handles CustomValidator1.ServerValidate
args.IsValid = Listbox.Items.Count > 0
End Sub
Private Sub PopulateListBox()
If NameTextBox.Text = "" Then
Else
' Get value from text box
Dim textBoxValue As String = Me.NameTextBox.Text
' Create new item to add to list box
Dim newItem As New ListItem(textBoxValue)
' Add item to list box and set selected index
Listbox.Items.Add(newItem)
Listbox.SelectedIndex = Listbox.Items.Count - 1
End If
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If IsPostBack Then
' Put call here to populate the listbox results from autocomplete extender selection
PopulateListBox()
End If
End Sub
By chance, is this:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If IsPostBack Then
' Put call here to populate the listbox results from autocomplete extender selection
PopulateListBox()
End If
End Sub
Is the IF statement supposed to be instead:
If Not IsPostBack Then
You currently have it not binding the first time, but everytime after.

VB.net/Asp.net loading a control programatically with a public property to be set

I have a vb.net asp application where I'm loading a control (from another control on a page). I want to set a variable between the two controls when it loads.
This is where I load the control:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim AuditControl As Control = LoadControl("~/controls/auditcompanies.ascx")
phCompanies.Controls.Add(AuditControl)
End Sub
On the control that's being loaded i've exposed the item i want to change as a property
Public Property resultType() As String
Get
Return m_resultType
End Get
Set(ByVal value As String)
m_resultType = value
End Set
End Property
Basically all it is doing is setting a parameter for my table adaptor
Public Sub Load_Data()
dtblog = New dsDECorp.ClientInfoDataTable
dtblog = tablog.GetAudits(m_resultType)
For Each rClient As dsDECorp.ClientInfoRow In dtblog
CID = rClient.ClientID
ClientName = rClient.CompanyName
Next
dtblog.Dispose()
End Sub
How do I pass the parameter through the property from the first control to the second when it loads?
Thanks
Tom
I'm a C# guy so forgive me if I make any syntax errors but the following should work for you:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim AuditControl As Control = LoadControl("~/controls/auditcompanies.ascx")
Dim AuditControlType As Type = AuditControl.GetType()
Dim AuditField As FieldInfo = AuditControlType.GetField("resultType")
AuditField.SetValue(AuditControlType, "Your Value")
phCompanies.Controls.Add(AuditControl)
End Sub

User enters code into TextBox, code gets added to URL (using session)

I'm using ASP.net 4.0 VB :)
I am using a session variable to add a user entered code into the url of each page. I can get the code to show up at the end of the page's URL that my textbox is on, but what do I add to every page to make sure that the session stays at the end of every URL that person visits during their session? This is the code from the page that the user enters their user code.
Protected Sub IBTextBoxButton_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles IBTextBoxButton.Click
Session("IB") = IBTextBox.Text
Dim IB As String = Session("IB")
End Sub
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
ProductID.Value = Request.QueryString("id")
If Session("IB") Is Nothing Then
tab4.Visible = "False"
Else
tab4.Visible = "True"
End If
End Sub
This is what I have in the page load of one of the other pages. What else do I add to make sure that variable is added to the URL of that page?
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim IB As String
IB = Session("IB")
End Sub
string url = Request.Url.ToString();
string newUrl = url + url.Contains("?") ? "&" : "?" + "ib=" + Server.UrlEncode(IBTextBox.Text);
Response.Redirect(newUrl);
return;
The approach I might use would be to create a base page class that all of your pages can inherit. The base page would then inherit the System.Web.UI.Page.
Within your base page class, create a property for IB and also handle the page load event.
In that event, check if the QueryString has the IB parameter in it. If it does, set the property to the value in the parameter.
Private _IB As String
Public Property IB() As String
Get
Return _IB
End Get
Set(ByVal value As String)
_IB = value
End Set
End Property
Public Function GetIB(ByVal url As String) As String
If Not(_IB = String.Empty) Then
If (url.Contains("?")) Then
Return "&IB=" & _IB
Else
Return url & "?IB=" & _IB
End If
Else
Return url
End If
End Function
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not (String.IsNullOrEmpty(Request.QueryString("IB"))) Then
_IB = Request.QueryString("IB")
End If
End Sub
Finally in your markup you would need to place something like the following at the end of all of your links:
next page
I threw this code into the Master Page to make sure that every page knows whether or not the Session is there. Thanks for all the help everyone!
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
Handles Me.Load
If Session("IB") Is Nothing Then
IBText.Visible = True
IBTextBox.Visible = True
IBTextBoxButton.Visible = True
Else
IBText.Visible = False
IBTextBox.Visible = False
IBTextBoxButton.Visible = False
lblIB.Visible = True
lblIB.Text = "Welcome, " + Session("First_Name") + " " + Session("Last_Name")
End If
End Sub

Asp.Net Null Reference Exception on Event Handler for Dynamic Controls

I've created some dynamic controls on page load and added an event handler to handle the click event of a dynamic link button. Within the sub of the click event handler, I need to reference some other (non-dynamic) controls on the page and change their value. However, I get a null reference exception - object not set to an instance of an object - each time I try to reference a control on the page (in this case label1). What am I doing wrong in creating these dynamic controls or with my event handler? Thanks!
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
'Get the data to populate the controls
Dim oMySqlData As New MySqlDataProvider
PlaceHolder1.Controls.Add(CreateExistingNotesHTML(oMySqlData.GetParentNotes("104628"), oMySqlData.GetChildNotes("104628")))
End Sub
Public Sub OnCommentClick(ByVal sender As Object, ByVal e As EventArgs)
'The event handler for the link buttons
Label1.Text = "You clicked " & DirectCast(sender, LinkButton).ID
End Sub
Public Function CreateExistingNotesHTML(ByVal dtParent As DataTable, ByVal dtChild As DataTable) As HtmlGenericControl
'The routine that creates the dynamic controls
Dim divContainer As New HtmlGenericControl("div")
For Each drParent As DataRow In dtParent.Rows()
divContainer.Controls.Add(WriteNote(drParent.Item("NoteId").ToString(), drParent.Item("UserName").ToString(), drParent.Item("ItemNote").ToString, CDate(drParent.Item("InsertDate")), "note"))
Next
Return divContainer
End Function
Private Function WriteNote(ByVal NoteId As String, ByVal UserName As String, ByVal ItemNote As String, ByVal InsertDate As DateTime, ByVal DivClass As String) As HtmlGenericControl
Dim div As New HtmlGenericControl("div")
div.ID = "d" & NoteId
div.Attributes.Add("class", DivClass)
div.Controls.Add(New LiteralControl(" ยท "))
'Add the dynamic link buttons
Dim lnkComment As New LinkButton
lnkComment.ID = "l" & NoteId
lnkComment.Text = "Comment"
lnkComment.Style("Text-decoration") = "none"
AddHandler lnkComment.Click, AddressOf oNotes.OnCommentClick
div.Controls.Add(lnkComment)
Return div
End Function
With this line
Dim oNotes As New EbayItemNotes
AddHandler lnkComment.Click, AddressOf oNotes.OnCommentClick
You are handling this event outside of your page and within the EbayItemNotes class, how does this class know anything of Label1 that resides in your page?
Could it be that you need to pass your label in as well..
Dim oNotes As EbayItemNotes = new EbayItemNotes(label1)
inside EbayItemNotes constructor
public sub New(lbl as Label) //store this label for use in event handler..

Resources