Timer not stopping after button is pressed - asp.net

I have a timer i press a button to start it and press a button to stop it but the button used to stop the timer does not work, i tried dispose,stop and enabled=false,all of them did not worked.The timer continues to send telegram messages even though i pressed stop. Frontend is a aspx form.
Dim aTimer As New System.Timers.Timer
Public Function TelegramSendMessage(ByVal apilToken As String, ByVal destID As String, ByVal text As String) As String
Dim a As String = apilToken
Dim urlString As String = "https://api.telegram.org/bot" + apilToken + "/sendMessage?chat_id=" + destID + "&text=" + text
Dim webclient As WebClient = New WebClient()
Return webclient.DownloadString(urlString)
End Function
Private Sub tick(ByVal sender As Object, ByVal e As System.Timers.ElapsedEventArgs)
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12
TelegramSendMessage(yourtoken,destinationid , "hi")
End Sub
Protected Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
aTimer.AutoReset = True
aTimer.Interval = 60000
AddHandler aTimer.Elapsed, AddressOf tick
aTimer.Enabled = True
End Sub
Protected Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
'aTimer.Dispose()
'aTimer.Enabled = False
aTimer.Stop()
End Sub

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 configure smtp settings

Imports System.Net.Mail
Partial Class ContactUs
Inherits System.Web.UI.Page
Protected Sub LinkButton1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles LinkButton1.Click
Dim username = User.Identity.Name.ToString
Response.Redirect("~/ViewCart_aspx/ViewCart.aspx?userID=" & username)
End Sub
Protected Sub CustomValidator1_ServerValidate(ByVal source As Object, ByVal args As System.Web.UI.WebControls.ServerValidateEventArgs) Handles CustomValidator1.ServerValidate
If txtComments.Text.Length > 200 Then
args.IsValid = False
Else
args.IsValid = True
End If
End Sub
Protected Sub WizardStep3_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles WizardStep3.Load
lblName.text = txtName.Text
lblEmail.Text = txtEmail.Text
lblComments.Text = txtComments.Text
lblRating.Text = txtRatings.Text
End Sub
Protected Sub Wizard1_FinishButtonClick(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.WizardNavigationEventArgs) Handles Wizard1.FinishButtonClick
SendMail(txtEmail.Text, txtComments.Text)
'MsgBox("Feedback Sent")
Response.Redirect("homepage_aspx/homepage.aspx")
End Sub
Private Sub SendMail(ByVal from As String, ByVal body As String)
Dim mMailSettings As System.Net.Configuration.MailSettingsSectionGroup
Dim mPort As Integer = mMailSettings.Smtp.Network.Port
Dim mHost As String = mMailSettings.Smtp.Network.Host
Dim mPassword As String = mMailSettings.Smtp.Network.Password
Dim mUsername As String = mMailSettings.Smtp.Network.UserName
'Dim mailServerName As String = "smtp.tricedeals.com"
'Dim message As MailMessage = New MailMessage(from, "admin#tricedeals.com", "feedback", body)
'Dim mailClient As SmtpClient = New SmtpClient
'mailClient.Host = mailServerName
'mailClient.Send(message)
'message.Dispose()
End Sub
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Response.Cache.SetCacheability(HttpCacheability.NoCache)
End Sub
End Class
what is wrong with my smtp settings??i cant send emails.please help me.
you can't send email because the send command is commented out. since you don't give more details or better explanation or exception message that's the only thing I can assume.

problems with postbacks events from dynamic controls in ASP.Net

I am currently working on a page that has a user control that builds a dynamic table. The control is originally loaded on the Page_Init event, and any time that an event is raised that changes the dynamic control the table is reloaded. The problem here is that if the control is changed between between loads, the events from the control do not fire. For instance, there are originally two rows in the table. An item is added to the table during the postback and now there are four rows (this table adds two rows at a time). Each row has one or two buttons. When the page is loaded and sent back to the browser, if a user clicks on any of the buttons, a postback occurs, but the event does not fire. What am I doing wrong here? How can I tell what control/event caused the postback? Below is the code for both the page, and the user control.
Payments.aspx:
Partial Public Class Payments
Inherits BasePage
Private foodMaster As Food
Private _check As BusinessLayer.CustomerCheck
Private Sub btnAddCheck_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnAddCheck.Click
' do nothing. the modal window is tied to the button via the modal window in the designer
End Sub
Private Sub btnCalendar_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles btnCalendar.Click
calCheckDate.Visible = Not calCheckDate.Visible
modCheck.Show()
End Sub
Private Sub btnCheckSave_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnCheckSave.Click
Try
If IsNothing(_check) Then _check = New BusinessLayer.CustomerCheck
If Me.CurrentCheck > 0 Then _check.CheckId = Me.CurrentCheck
_check.CheckNumber = txtCheckNumber.Text
_check.CheckDate = CDate(txtCheckDate.Text)
_check.CheckAmount = CDbl(txtCheckAmount.Text)
_check.DepositId = Me.CurrentDeposit
_check.Save()
LoadControls()
' reset the current check to not get confused after an edit
Me.CurrentCheck = 0
SetupNewCheck()
Catch ex As Exception
lblMessage.Text = "Could not save check."
lblMessage.Visible = True
modCheck.Show()
End Try
End Sub
Private Sub calCheckDate_SelectionChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles calCheckDate.SelectionChanged
txtCheckDate.Text = calCheckDate.SelectedDate.ToShortDateString()
calCheckDate.Visible = False
modCheck.Show()
End Sub
Private Sub cvFutureDate_ServerValidate(ByVal source As Object, ByVal args As System.Web.UI.WebControls.ServerValidateEventArgs) Handles cvFutureDate.ServerValidate
Try
Dim depositDate As DateTime = DateTime.Parse(txtCheckDate.Text)
Dim futureDate As DateTime = Now.AddDays(1)
Dim tomorrow As New DateTime(futureDate.Year, futureDate.Month, futureDate.Day)
args.IsValid = CBool(depositDate < tomorrow)
Catch
args.IsValid = False
End Try
End Sub
Private Sub cvInvalidAmount_ServerValidate(ByVal source As Object, ByVal args As System.Web.UI.WebControls.ServerValidateEventArgs) Handles cvInvalidAmount.ServerValidate
Try
Double.Parse(txtCheckAmount.Text)
Catch
args.IsValid = False
End Try
End Sub
Private Sub cvInvalidDate_ServerValidate(ByVal source As Object, ByVal args As System.Web.UI.WebControls.ServerValidateEventArgs) Handles cvInvalidDate.ServerValidate
Try
DateTime.Parse(txtCheckDate.Text)
Catch
args.IsValid = False
End Try
End Sub
Private Sub DepositEditing()
foodMaster.Deposit.Load(Me.CurrentDeposit)
foodMaster.ShowDepositWindow()
End Sub
Private Sub DepositSaved()
dihHeader.Deposit.Load(Me.CurrentDeposit)
dihHeader.Reload()
End Sub
Private Sub Payments_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Init
LoadControls()
End Sub
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
foodMaster = DirectCast(Me.Master, Food)
AddHandler foodMaster.SaveClicked, AddressOf DepositSaved
AddHandler foodMaster.EditButtonClicked, AddressOf DepositEditing
If IsPostBack = False Then
Me.CurrentCheck = 0
SetupNewCheck()
End If
End Sub
Private Sub pcPayments_ApplyFundsClicked(ByVal CheckId As Integer) Handles pcPayments.ApplyFundsClicked
End Sub
Private Sub pcPayments_DeleteClicked(ByVal CheckId As Integer) Handles pcPayments.DeleteClicked
Try
If Me.CurrentCheck = CheckId Then Me.CurrentCheck = 0
_check = New BusinessLayer.CustomerCheck
_check.CheckId = CheckId
_check.DeleteAllPayments()
_check.Delete()
LoadControls()
Catch
End Try
End Sub
Private Sub pcPayments_EditClicked(ByVal CheckId As Integer) Handles pcPayments.EditClicked
Me.CurrentCheck = CheckId
_check = New BusinessLayer.CustomerCheck(CheckId)
txtCheckAmount.Text = _check.CheckAmount.ToString("0.00")
txtCheckDate.Text = _check.CheckDate.ToShortDateString
calCheckDate.SelectedDate = _check.CheckDate
txtCheckNumber.Text = _check.CheckNumber
modCheck.Show()
End Sub
Private Sub LoadControls()
Dim checks As New BusinessLayer.CustomerCheckCollection()
checks.LoadByDeposit(Me.CurrentDeposit)
pcPayments.Checks = checks
pcPayments.Reload()
dihHeader.Deposit.Load(Me.CurrentDeposit)
dihHeader.TotalCheckAmount = pcPayments.TotalCheckAmount
dihHeader.TotalAppliedAmount = pcPayments.TotalAmountApplied
dihHeader.Reload()
End Sub
Private Sub SetupNewCheck()
_check = Nothing
txtCheckDate.Text = Now.ToShortDateString()
calCheckDate.SelectedDate = Now
txtCheckAmount.Text = String.Empty
txtCheckNumber.Text = String.Empty
End Sub
End Class
PaymentsControl.ascx
Public Partial Class PaymentsControl
Inherits System.Web.UI.UserControl
Private _checks As BusinessLayer.CustomerCheckCollection
Private _applied As Double
Public Event ApplyFundsClicked(ByVal CheckId As Integer)
Public Event DeleteClicked(ByVal CheckId As Integer)
Public Event EditClicked(ByVal CheckId As Integer)
Public Sub New()
_checks = New BusinessLayer.CustomerCheckCollection
_applied = 0
End Sub
Private Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
'If IsPostBack = False Then
' BindChecks()
'End If
End Sub
Private Sub ApplyButtonClicked(ByVal sender As Object, ByVal e As EventArgs)
RaiseEvent ApplyFundsClicked(DirectCast(sender, LinkButton).CommandArgument)
End Sub
Private Sub DeleteButtonClicked(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs)
RaiseEvent DeleteClicked(DirectCast(sender, ImageButton).CommandArgument)
End Sub
Private Sub EditButtonClicked(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs)
RaiseEvent EditClicked(DirectCast(sender, ImageButton).CommandArgument)
End Sub
Private Sub BindChecks()
tblChecks.Rows.Clear()
tblChecks.Rows.Add(BuildTableHeader())
_applied = 0
For i As Int16 = 0 To _checks.Count - 1
_checks(i).LoadAllPayments()
_applied += _checks(i).TotalAmountApplied
tblChecks.Rows.Add(BuildCheckRow(_checks(i)))
tblChecks.Rows.Add(BuildInvoiceRow(_checks(i)))
Next
If tblChecks.Rows.Count = 1 Then tblChecks.Visible = False
End Sub
Private Function BuildCheckRow(ByVal Check As BusinessLayer.CustomerCheck) As TableRow
Dim checkNumberCell As New TableCell()
Dim checkDateCell As New TableCell()
Dim checkAmountCell As New TableCell()
Dim totalAppliedCell As New TableCell()
checkNumberCell.Text = Check.CheckNumber
checkDateCell.Text = Check.CheckDate.ToShortDateString()
checkAmountCell.Text = Check.CheckAmount.ToString("C")
totalAppliedCell.Text = Check.TotalAmountApplied.ToString("C")
If Check.TotalAmountApplied <> Check.CheckAmount Then totalAppliedCell.ForeColor = Drawing.Color.Red
Dim myRow As New TableRow
myRow.Cells.Add(BuildCheckControlCell(Check.CheckId))
myRow.Cells.Add(checkNumberCell)
myRow.Cells.Add(checkDateCell)
myRow.Cells.Add(checkAmountCell)
myRow.Cells.Add(totalAppliedCell)
Return myRow
End Function
Private Function BuildCheckControlCell(ByVal CheckId As Integer) As TableCell
Dim editButton As New ImageButton()
editButton.CommandArgument = CheckId
editButton.CausesValidation = False
editButton.AlternateText = "Edit"
editButton.ImageUrl = "~/images/icons/bullet_edit.png"
AddHandler editButton.Click, AddressOf EditButtonClicked
Dim deleteButton As New ImageButton
deleteButton.CommandArgument = CheckId
deleteButton.CausesValidation = False
deleteButton.AlternateText = "Delete"
deleteButton.ImageUrl = "~/images/icons/bullet_cross.png"
deleteButton.Attributes.Add("onclick", "return confirmDelete()")
AddHandler deleteButton.Click, AddressOf DeleteButtonClicked
Dim blankSpace As New Literal()
blankSpace.Text = " "
Dim myCell As New TableCell
myCell.Controls.Add(editButton)
myCell.Controls.Add(blankSpace)
myCell.Controls.Add(deleteButton)
Return myCell
End Function
Private Function BuildInvoiceRow(ByVal Check As BusinessLayer.CustomerCheck) As TableRow
Dim invoiceDetailCell As New TableCell
invoiceDetailCell.ColumnSpan = 4
invoiceDetailCell.Controls.Add(BuildInvoiceDetailTable(Check.Payments))
Dim myRow As New TableRow
myRow.Cells.Add(BuildInvoiceControlCell(Check.CheckId))
myRow.Cells.Add(invoiceDetailCell)
Return myRow
End Function
Private Function BuildInvoiceControlCell(ByVal CheckId As Integer) As TableCell
Dim text As New Literal
text.Text = "Invoices for check:<br />"
Dim applyButton As New LinkButton
applyButton.CommandArgument = CheckId
applyButton.CausesValidation = False
applyButton.Text = "Apply Funds"
AddHandler applyButton.Click, AddressOf ApplyButtonClicked
Dim myCell As New TableCell
myCell.Controls.Add(text)
myCell.Controls.Add(applyButton)
Return myCell
End Function
Private Function BuildInvoiceDetailTable(ByVal Payments As BusinessLayer.PaymentTransactionCollection) As Table
Dim myTable As New Table
myTable.CssClass = "tableSub"
myTable.CellPadding = "0"
myTable.CellSpacing = "0"
myTable.BorderWidth = "0"
myTable.Rows.Add(BuildInvoiceDetailHeader())
For i As Integer = 0 To Payments.Count - 1
myTable.Rows.Add(BuildPaymentRow(Payments(i)))
Next
If myTable.Rows.Count = 1 Then myTable.Visible = False
Return myTable
End Function
Private Function BuildInvoiceDetailHeader() As TableRow
Dim customerCell As New TableHeaderCell
Dim invoiceCell As New TableHeaderCell
Dim dueCell As New TableHeaderCell
Dim paymentCell As New TableHeaderCell
customerCell.Text = "Customer"
invoiceCell.Text = "Invoice number"
dueCell.Text = "Amount due"
paymentCell.Text = "Payment amount"
Dim myRow As New TableRow
myRow.Cells.Add(customerCell)
myRow.Cells.Add(invoiceCell)
myRow.Cells.Add(dueCell)
myRow.Cells.Add(paymentCell)
Return myRow
End Function
Private Function BuildPaymentRow(ByVal Payment As BusinessLayer.PaymentTransaction) As TableRow
Dim customerCell As New TableCell
Dim invoiceCell As New TableCell
Dim amountDueCell As New TableCell
Dim paymentCell As New TableCell
'Payment.Customer.Load()
customerCell.Text = Payment.Customer.NumberAndName
invoiceCell.Text = Payment.Invoice.InvoiceNumber
amountDueCell.Text = Payment.Invoice.AmountDue.ToString("C")
paymentCell.Text = Payment.PaymentAmount.ToString("C")
Dim myRow As New TableRow
myRow.Cells.Add(customerCell)
myRow.Cells.Add(invoiceCell)
myRow.Cells.Add(amountDueCell)
myRow.Cells.Add(paymentCell)
Return myRow
End Function
Private Function BuildTableHeader() As TableRow
Dim blankCell As New TableHeaderCell()
Dim checkNumberCell As New TableHeaderCell()
Dim checkDateCell As New TableHeaderCell()
Dim checkAmountCell As New TableHeaderCell()
Dim totalUnappliedCell As New TableHeaderCell()
checkNumberCell.Text = "Check number"
checkDateCell.Text = "Check date"
checkAmountCell.Text = "Check amount"
totalUnappliedCell.Text = "Total unapplied"
Dim myRow As New TableRow
myRow.Cells.Add(blankCell)
myRow.Cells.Add(checkNumberCell)
myRow.Cells.Add(checkDateCell)
myRow.Cells.Add(checkAmountCell)
myRow.Cells.Add(totalUnappliedCell)
Return myRow
End Function
Public Sub Reload()
BindChecks()
End Sub
Public Property Checks() As BusinessLayer.CustomerCheckCollection
Get
Return _checks
End Get
Set(ByVal value As BusinessLayer.CustomerCheckCollection)
_checks = value
End Set
End Property
Public ReadOnly Property TotalCheckAmount() As Double
Get
Return _checks.TotalCheckAmount
End Get
End Property
Public ReadOnly Property TotalAmountApplied() As Double
Get
Return _applied
End Get
End Property
End Class
You need to assign the Id property to each dynamically added server control that will serve up postback events. Also, on postback, I believe that the dynamically added controls need to be recreated with the same id in order for postback methods and viewstate to function correctly.

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