Asp.net losing values of variables - asp.net

I am trying to write my first WebApplication in ASP.NET. Here is my code:
Public Class WebForm2
Inherits System.Web.UI.Page
Public n As Integer
Public zetony As Integer
Public liczba As Boolean
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
End Sub
Private Function TextBox1_Validate(Cancel As Boolean)
If Not IsNumeric(TextBox1.Text) Then
MsgBox("Prosze podaj liczbe dobry uzytkowniku :)", vbInformation)
Cancel = True
Else : Cancel = False
End If
Return Cancel
End Function
Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
liczba = TextBox1_Validate(liczba)
If (liczba = False) Then
n = Convert.ToInt32(TextBox1.Text)
Label2.Text = n
End If
End Sub
Protected Sub graj()
Label2.Text = n
End Sub
Protected Sub Image1_Click(sender As Object, e As ImageClickEventArgs) Handles ImageButton1.Click
If zetony < 2 Then
n -= 1
ImageButton1.ImageUrl = "red_coin.gif"
zetony += 1
End If
End Sub
Protected Sub Image2_Click(sender As Object, e As ImageClickEventArgs) Handles ImageButton2.Click
If zetony < 2 Then
n -= 1
ImageButton2.ImageUrl = "red_coin.gif"
zetony += 1
End If
End Sub
Protected Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
graj()
End Sub
End Class
My problem is that, only on Button1_Click I got proper value. When I try to call Sub graj() value of n is alwayes 0.

HTTP is stateless. This means that for every request a new instance of the class WebForm2 gets created. So if you set the value of n inside Button1_Click it will not be preserverd when you access it from Button2_Click since it's a different instance.
To save your data across requests there are several possibilities, to name a few:
Save it in a database
Save it in the Application-object (this is shared across all users:
// setting the value
HttpContext.Current.Application("n") = "somevalue";
// Getting the value
string test = HttpContext.Current.Application("n");
Save it in the session-state (this is shared across all requests for one user):
// setting the value
HttpContext.Current.Session("n") = "somevalue";
// Getting the value
string test = HttpContext.Current.Session("n");

Related

vb.net CefSharp.Windows document.getElementById

We used webbrowser control to login website in VB.NET, now we are going to us CefSharp.
We have made a simple test form. Clicking on the button sets the "toegangscode". It works, but when I go to next field wachtwoord (password) and type 1 first character the "toegangscode" field will be made empty. What I am doing wrong ?
Public Class Form1
Public WithEvents browser As ChromiumWebBrowser
Public Sub New()
' This call is required by the designer.
InitializeComponent()
Dim settings As New CefSharp.WinForms.CefSettings()
CefSharp.Cef.Initialize(settings)
browser = New CefSharp.WinForms.ChromiumWebBrowser("https://diensten.kvk.nl/inloggen.html") With {
.Dock = DockStyle.Fill}
Panel1.Controls.Add(browser)
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim jsScript1 = <js><![CDATA[document.getElementById("username").focus();]]></js>.Value
browser.ExecuteScriptAsync(jsScript1)
Dim jsScript2 As String = <js><![CDATA[document.getElementById("username").value = "xxxxxx";]]></js>.Value
browser.ExecuteScriptAsync(jsScript2)
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim bCanExecuteJavascriptInMainFrame As Boolean = browser.CanExecuteJavascriptInMainFrame
Dim bIsBrowserInitialized As Boolean = browser.IsBrowserInitialized
If bIsBrowserInitialized Then
browser.ShowDevTools()
End If
End Sub
End Class

Call a function from the Login Control in vb.net

Trying to call a function in code behind but not working - one suggestion was to use the OnAuthenticate instead of the OnClick however this requires a rewrite of the entire authentication process.
<asp:Login ID="Login1" runat="server" OnClick="MyButton" DestinationPageUrl="~/Receipt.aspx"
UserNameLabelText="User Name (From: mysite.com):"
PasswordRecoveryText="Forgot User Name or Password?"
PasswordRecoveryUrl="~/GetPassword.aspx">
</asp:Login>
vb code:
Protected Sub MyButton(ByVal sender As Object, ByVal e As System.EventArgs)
Dim username As String = Login1.UserName
Dim currentDateTime As DateTime = DateTime.Now.AddHours(3)
Dim filepath As String = Server.MapPath("~") + "\debug.txt"
Using writer As StreamWriter = File.AppendText(filepath)
writer.WriteLine(username)
writer.WriteLine(currentDateTime)
writer.WriteLine("")
End Using
End Sub
Revised Code:
Imports System.IO
Imports System.Data
Partial Class Login
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim xUserName As String = User.Identity.Name()
'UpdateLastLoginDate(xUserName)
End Sub
Protected Sub MyButton(ByVal sender As Object, ByVal e As System.EventArgs)
Dim username As String = Login1.UserName
Dim pw As String = Login1.Password
Dim currentDateTime As DateTime = DateTime.Now.AddHours(3)
Dim filepath As String = Server.MapPath("~") + "\debug.txt"
Using writer As StreamWriter = File.AppendText(filepath)
writer.WriteLine(username)
writer.WriteLine(pw)
writer.WriteLine(currentDateTime)
writer.WriteLine("REMOTE_ADDR: " + Request.Servervariables("REMOTE_ADDR"))
writer.WriteLine("USER_AGENT: " + Request.Servervariables("HTTP_USER_AGENT"))
writer.WriteLine("LOCAL_ADDR: " + Request.Servervariables("LOCAL_ADDR"))
writer.WriteLine("LOGON_USER: " + Request.Servervariables("LOGON_USER"))
'writer.WriteLine(Request.Servervariables("ALL_HTTP"))
writer.WriteLine("")
End Using
End Sub
Protected Sub Page_PreInit(sender As Object, e As EventArgs)
WireLoginControlButtonClickEvent(Login1)
End Sub
Private Sub WireLoginControlButtonClickEvent(parent As Control)
For Each ctrl As Control In parent.Controls
If TypeOf ctrl Is Button Then
AddHandler DirectCast(ctrl, Button).Click, Function() (MyFunction())
ElseIf ctrl.HasControls() Then
WireLoginControlButtonClickEvent(ctrl)
End If
Next
End Sub
Private Function MyFunction() As String
Response.Write("Function Called")
Return Nothing
End Function
End Class
Give this a try:
Protected Sub Page_PreInit(sender As Object, e As EventArgs)
WireLoginControlButtonClickEvent(Login1)
End Sub
Private Sub WireLoginControlButtonClickEvent(parent As Control)
For Each ctrl As Control In parent.Controls
If TypeOf ctrl Is Button Then
AddHandler DirectCast(ctrl, Button).Click, AddressOf MyFunction
ElseIf ctrl.HasControls() Then
WireLoginControlButtonClickEvent(ctrl)
End If
Next
End Sub
Private Sub MyFunction(sender As Object, e As EventArgs)
Response.Write("Function Called")
End Sub

How to fix the error "Object reference not set to an instance of an object"?

In this program (VB, ASP.NET 2010) I create three fields: accno, name and balance, and the following buttons: create, destroy, set and get.
But while clicking on set or get method it gives the following exception: object reference not set to an instance of an object
Default.aspx.vb
Partial Class _Default
Inherits System.Web.UI.Page
Dim obj As account 'declaring the obj of class account
Protected Sub btn_create_Click(sender As Object, e As System.EventArgs) Handles btn_create.Click
obj = New account 'initializing the object obj on class accounts
End Sub
Protected Sub btn_set_Click(sender As Object, e As System.EventArgs) Handles btn_set.Click
'sending the values from textboxes to accounts class through method setdata
Try
obj.setdata(CInt(txt_accno.Text), (txt_name.Text), CInt(txt_bal.Text))
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Protected Sub btn_get_Click(sender As Object, e As System.EventArgs) Handles btn_get.Click
'calling the method getdata to view the output
Try
obj.getdata()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Protected Sub btn_destroy_Click(sender As Object, e As System.EventArgs) Handles btn_destroy.Click
'calling the constructor
obj = Nothing
End Sub
End Class
Account.vb
Imports Microsoft.VisualBasic
Public Class account
Private accno As Integer
Private acc_name As String
Private bal As Integer
'constructor
Public Sub New()
MsgBox("object created")
End Sub
'public method to populate above three private variable
Public Sub setdata(ByVal a As Integer, ByVal b As String, ByVal c As Integer)
Me.accno = a
Me.acc_name = b
Me.bal = c
End Sub
Public Sub getdata()
MsgBox(Me.accno.ToString + vbNewLine + Me.acc_name + vbNewLine + Me.bal.ToString)
End Sub
'destructor
Protected Overrides Sub finalize()
MsgBox("object destroyed")
End Sub
End Class
You have use New Keyword for Initializing Objects...
Dim obj As NEW account
Default.aspx.vb Partial Class _Default Inherits System.Web.UI.Page
'declaring the obj of class account
Dim obj As NEW account
Protected Sub btn_create_Click(sender As Object, e As System.EventArgs) Handles btn_create.Click
'initializing the object obj on class accounts
obj = New account
End Sub
Protected Sub btn_set_Click(sender As Object, e As System.EventArgs) Handles btn_set.Click
'sending the values from textboxes to accounts class through method setdata
Try
obj.setdata(CInt(txt_accno.Text), (txt_name.Text), CInt(txt_bal.Text))
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Protected Sub btn_get_Click(sender As Object, e As System.EventArgs) Handles btn_get.Click
'calling the method getdata to view the output
Try
obj.getdata()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Protected Sub btn_destroy_Click(sender As Object, e As System.EventArgs) Handles btn_destroy.Click
'calling the constructor
obj = Nothing
End Sub
End Class
Please mark it as answer if it's working.
use below code. You need to initialize in page load method and need to check is postback property.
Default.aspx.vb Partial Class _Default Inherits System.Web.UI.Page
'declaring the obj of class account
Dim obj As account
Sub Page_Load(ByVal Sender As System.Object, ByVal e As System.EventArgs)
if not ispostback then
obj = New account
end
End Sub
Protected Sub btn_create_Click(sender As Object, e As System.EventArgs) Handles btn_create.Click
'initializing the object obj on class accounts
obj = New account
End Sub
Protected Sub btn_set_Click(sender As Object, e As System.EventArgs) Handles btn_set.Click
'sending the values from textboxes to accounts class through method setdata
Try
obj.setdata(CInt(txt_accno.Text), (txt_name.Text), CInt(txt_bal.Text))
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Protected Sub btn_get_Click(sender As Object, e As System.EventArgs) Handles btn_get.Click
'calling the method getdata to view the output
Try
obj.getdata()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Protected Sub btn_destroy_Click(sender As Object, e As System.EventArgs) Handles btn_destroy.Click
'calling the constructor
obj = Nothing
End Sub
End Class

Getting an ASP.NET error System.NullReferenceException: Object reference not set to an instance of an object?

I am completely new to ASP.NET and VB as well as C#. I am trying to add customers to a contact list out of a DB. Then the list can be referenced to call them up.
But when I try to run it I get System.NullReferenceException: Object reference not set to an instance of an object. In line 19.
Here is my code:
Page 1 is default page...it connects to the database and grabs the contact information and allows me to select the current contact and add them to a listbox on a separate page:
Imports System.Data
Partial Class _Default
Inherits System.Web.UI.Page
Private SelectedCustomer As Customer
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) _
Handles Me.Load
If Not IsPostBack Then
ddlCustomers.DataBind()
End If
SelectedCustomer = Me.GetSelectedCustomer
Me.DisplayCustomer()
End Sub
Private Function GetSelectedCustomer() As Customer
Dim dvTable As dataview = CType(AccessDataSource1.Select( _
DataSourceSelectArguments.Empty), dataview)
dvTable.RowFilter = "CustomerID = " & ddlCustomers.SelectedValue
Dim drvRow As DataRowView = dvTable(0)
Dim customer As New Customer
customer.CustomerID = CInt(drvRow("CustomerID"))
customer.Name = drvRow("Name").ToString
customer.Address = drvRow("Address").ToString
customer.City = drvRow("City").ToString
customer.State = drvRow("State").ToString
customer.ZipCode = drvRow("ZipCode").ToString
customer.Phone = drvRow("Phone").ToString
customer.Email = drvRow("Email").ToString
Return customer
End Function
Private Sub DisplayCustomer()
lblAddress.Text = SelectedCustomer.Address
lblCityStateZip.Text = SelectedCustomer.City & ", " _
& SelectedCustomer.State & " " _
& SelectedCustomer.ZipCode
lblPhone.Text = SelectedCustomer.Phone
lblEmail.Text = SelectedCustomer.Email
End Sub
Protected Sub btnAdd_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnAdd.Click
If Page.IsValid Then
Dim customerItem As New Customer
customerItem.Name = SelectedCustomer.ToString
Me.AddToCustomer(customerItem)
Response.Redirect("CustomerList.aspx")
End If
End Sub
Private Sub AddToCustomer(ByVal customerItem As Customer)
Dim customer As SortedList = Me.GetCustomer
Dim customerID As String = SelectedCustomer.CustomerID
If customer.ContainsKey(customerID) Then
customerItem = CType(customer(customerID), Customer)
Else
customer.Add(customerID, customerItem)
End If
End Sub
Private Function GetCustomer() As SortedList
If Session("Customer") Is Nothing Then
Session.Add("Customer", New SortedList)
End If
Return CType(Session("Customer"), SortedList)
End Function
End Class
The next bit of code allows me to add the contact to a list box:
Partial Class Default2
Inherits System.Web.UI.Page
Private Customer As SortedList
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Customer = Me.GetCustomer
If Not IsPostBack Then Me.DisplayCustomer()
End Sub
Private Function GetCustomer() As SortedList
If Session("Customer") Is Nothing Then
Session.Add("Customer", New SortedList)
End If
Return CType(Session("Cart"), SortedList)
End Function
Private Sub DisplayCustomer()
lstCustomer.Items.Clear()
Dim customerItem As Customer
For Each customerEntry As DictionaryEntry In Customer
customerItem = CType(customerEntry.Value, Customer)
lstCustomer.Items.Add(customerItem.Name)
Next
End Sub
Protected Sub lstCustomer_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles lstCustomer.SelectedIndexChanged
End Sub
End Class
The error occurs on line 19 (For Each customerEntry As DictionaryEntry In Customer) in the second set of code from the default2 class. Any ideas? I am completely new to ASP.NET just trying to learn. I more at home on PHP, Java, and Actionscript unfortunately.
I think the problem is in this function
Private Function GetCustomer() As SortedList
If Session("Customer") Is Nothing Then
Session.Add("Customer", New SortedList)
End If
Return CType(Session("Cart"), SortedList)
End Function
You initialise Customer here but then pull out of Session("Cart")
I think what you meant to do is
Private Function GetCustomer() As SortedList
If Session("Customer") Is Nothing Then
Session.Add("Customer", New SortedList)
End If
Return CType(Session("Customer"), SortedList)
End Function
Now customer should always be initialised whereas before it might not have been which would cause the NullReferenceException that you are getting.

Can I add buttons with events to a custom treeNode?

I extended treeview, treenode, and nodetype so I could have custom nodes. Certain nodes have image buttons on them allowing them to add a child node or delete the node. I can't handle any of the events from my buttons.
Public Class ContentTreeView
Inherits TreeView
Public Event OnAddChild(ByVal sender As Object, ByVal e As EventArgs)
Public Event OnDelete(ByVal sender As Object, ByVal e As EventArgs)
Private _AddImageURL As String = String.Empty
Private _DeleteImageURL As String = String.Empty
Public Property AddImageURL() As String
Get
Return _AddImageURL
End Get
Set(ByVal value As String)
_AddImageURL = value
End Set
End Property
Public Property DeleteImageURL() As String
Get
Return _DeleteImageURL
End Get
Set(ByVal value As String)
_DeleteImageURL = value
End Set
End Property
Protected Overrides Function CreateNode() As TreeNode
Dim retval As ContentTreeNode = New ContentTreeNode(AddImageURL, DeleteImageURL)
AddHandler retval.OnAddChild, AddressOf ContentNode_AddChild
AddHandler retval.OnDelete, AddressOf ContentNode_Delete
Return retval
End Function
Protected Sub ContentNode_AddChild(ByVal sender As Object, ByVal e As EventArgs)
RaiseEvent OnAddChild(Nothing, Nothing)
End Sub
Protected Sub ContentNode_Delete(ByVal sender As Object, ByVal e As EventArgs)
RaiseEvent OnDelete(Nothing, Nothing)
End Sub
Public Class ContentTreeNode
Inherits TreeNode
Public Event OnAddChild(ByVal sender As Object, ByVal e As EventArgs)
Public Event OnDelete(ByVal sender As Object, ByVal e As EventArgs)
Private _AddImageURL As String = String.Empty
Private _DeleteImageURL As String = String.Empty
Private btnAddChild As ImageButton
Private btnDelete As ImageButton
Public Sub New(ByVal AddImageURL_ As String, ByVal DeleteImageURL_ As String)
_AddImageURL = AddImageURL_
_DeleteImageURL = DeleteImageURL_
End Sub
Public Property AddImageURL() As String
Get
Return _AddImageURL
End Get
Set(ByVal value As String)
_AddImageURL = value
End Set
End Property
Public Property DeleteImageURL() As String
Get
Return _DeleteImageURL
End Get
Set(ByVal value As String)
_DeleteImageURL = value
End Set
End Property
Protected Overrides Sub RenderPreText(ByVal writer As HtmlTextWriter)
End Sub
Protected Overrides Sub RenderPostText(ByVal writer As HtmlTextWriter)
CreateChildControls()
If GetTreeNodeType() <> ContentTreeNodeTypes.Root Then
btnAddChild.RenderControl(writer)
If GetTreeNodeType() <> ContentTreeNodeTypes.Category Then
btnDelete.RenderControl(writer)
End If
End If
End Sub
Private Function GetTreeNodeType() As TreeNodeTypes
Dim leaf As TreeNodeTypes = TreeNodeTypes.Leaf
If ((Me.Depth = 0) AndAlso (Me.ChildNodes.Count > 0)) Then
Return ContentTreeNodeTypes.Root
End If
If Me.Depth = 1 Then
Return ContentTreeNodeTypes.Category
End If
If ((Me.ChildNodes.Count <= 0) AndAlso Not Me.PopulateOnDemand) Then
Return leaf
End If
Return ContentTreeNodeTypes.Parent
End Function
Protected Sub CreateChildControls()
'Controls.Clear()
'***Creat Add Button***
btnAddChild = New ImageButton()
btnAddChild.ID = "btnAddChild"
btnAddChild.ImageUrl = AddImageURL
btnAddChild.ToolTip = "Add Child"
AddHandler btnAddChild.Click, AddressOf btnAddChild_Click
'***Create DeleteButton***
btnDelete = New ImageButton()
btnDelete.ID = "btnDelete"
btnDelete.ImageUrl = DeleteImageURL()
btnDelete.ToolTip = "Delete Page"
AddHandler btnDelete.Click, AddressOf btnDelete_Click
''***Add Controls***
'Me.Controls.Add(btnAddChild)
'Me.Controls.Add(btnDelete)
End Sub
Protected Sub btnAddChild_Click(ByVal sender As Object, ByVal e As EventArgs)
RaiseEvent OnAddChild(Nothing, Nothing)
End Sub
Protected Sub btnDelete_Click(ByVal sender As Object, ByVal e As EventArgs)
RaiseEvent OnDelete(Nothing, Nothing)
End Sub
Public Enum ContentTreeNodeTypes
All = 7
Leaf = 4
None = 0
Parent = 2
Root = 1
Category = 3
End Enum
End Class
End Class
1) Can I implement something like IPostBackEventHandler?
2) Is this possible since treeNode isn't a control/webcontrol?
Any help is appreciated... Thanks!!!
I think the problem is timing related, meaning the child controls are added to late in the ASP.Net page lifecycle for the event to be executed.
This might solve the issue:
Compose the whole tree structure as early as possible, e.g. in the Init event of the page.
Append the child ImageButton in the constructor of the ContentTreeNode.
Alternatively you could use a javascript context-menu so you wouldn't need to append any child-controls to the TreeNode...
After reading this post. I decided to use the following solution. First I changed my CreateChildControls method to:
Protected Sub CreateChildControls()
Dim page As Page = HttpContext.Current.CurrentHandler
Dim csm As ClientScriptManager = page.ClientScript
Dim control As WebControl = page.Master.FindControl(_ContainerID).FindControl(_ContentTreeViewID)
'***Creat Add Button***
btnAddChild = New ImageButton()
btnAddChild.ID = "btnAddChild"
btnAddChild.ImageUrl = AddImageURL
btnAddChild.ToolTip = "Add Child"
btnAddChild.Attributes.Add("onClick", csm.GetPostBackEventReference(control, String.Format("{0}:{1}", Me.Value, "Add")))
'***Create DeleteButton***
btnDelete = New ImageButton()
btnDelete.ID = "btnDelete"
btnDelete.ImageUrl = DeleteImageURL()
btnDelete.ToolTip = "Delete Page"
btnDelete.Attributes.Add("onClick", csm.GetPostBackEventReference(control, String.Format("{0}:{1}", Me.Value, "Delete")))
End Sub
Then I had to implement IPostBackEventHandler in the custom treeview to handle the postback events. Maybe not the best solution but it works well with custom event args.

Resources