Can I add buttons with events to a custom treeNode? - asp.net

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.

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

asp.net server control not saving state properly

I am trying to create an ASP.net server control that uses controls from the AjaxControlToolkit. Essentially, the control is a dropdownlist and a button. When the user clicks the button, a modal dialog (modalPopupExtender) opens. The dialog has a checkboxlist with a list of options to chose from. When the user selects their choice(s) and hits the Ok button, in the dialog, the dialog closes and the selected choices should get added to the dropdownlist. What is happening, though, is that when the user makes their selection and hits OK only the last item in the Checkboxlist gets added. I think it may have something to do with the inherited functions I override. Can anyone tell me what I may be doing wrong? Here is the relevant code:
<DefaultProperty("Text"), ToolboxData("<{0}:myServerControl runat=server>
</{0}:myServerControl >")> _
Public Class myServerControl
Inherits CompositeControl
Implements INamingContainer, IPostBackEventHandler
Private myDropDownListAs New DropDownList
Private addPlant As New Button
Private _updatePanel As UpdatePanel
Private _modalExtenderOne As AjaxControlToolkit.ModalPopupExtender
Private lblWarning As Label
Private cb1 As New CheckBoxList
Private btnSavePlants As New Button
Private btnCancel As New Button
Protected Overrides Function SaveViewState() As Object
Return New Pair(MyBase.SaveViewState(), Nothing)
End Function
Protected Overrides Sub LoadViewState(ByVal savedState As Object)
MyBase.LoadViewState(CType(savedState, Pair).First)
EnsureChildControls()
End Sub
Protected Overrides Sub CreateChildControls()
createDynamicControls()
MyBase.CreateChildControls()
End Sub
Protected Overrides Sub OnInit(ByVal e As System.EventArgs)
MyBase.OnInit(e)
End Sub
Protected Overrides Sub OnLoad(ByVal e As System.EventArgs)
MyBase.OnLoad(e)
End Sub
Private Sub createDynamicControls()
Controls.Clear()
AddHandler btnSavePlants.Click, AddressOf saveItems_Click
_updatePanel = New UpdatePanel
Dim myTable As New Table
myTable = buildControl() ' a funciton that returns a built table
Dim myPanel As New Panel
myPanel = buildDialog() 'a function taht returns a build modal dialog
_updatePanel.ContentTemplateContainer.Controls.Add(myTable)
_updatePanel.ContentTemplateContainer.Controls.Add(myPanel)
Me.Controls.Add(_updatePanel)
End Sub
Protected Sub saveItems_Click(ByVal sender As Object, ByVal e As EventArgs)
Me.myDropDownList.Items.Clear()
Try
For Each i As ListItem In Me.cb1.Items
If (i.Selected = True) Then
Dim newLi As New ListItem
With newLi
.Selected = False
.Text = i.Text
.Value = i.Value
End With
Me.myDropDownList.Items.Add(newLi)
Else
End If
Next
Catch ex As Exception
End Try
End Sub
Public Sub bindSelections(ByVal myList As List(Of myObject))
For Each p As myObjectIn myList
Dim newLI As New ListItem
newLI.Value = p.EquipmentPK
newLI.Text = p.EquipmentID
Me.cb1.Items.Add(newLI)
Next
End Sub
Public Sub RaisePostBackEvent(ByVal eventArgument As String) Implements System.Web.UI.IPostBackEventHandler.RaisePostBackEvent
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.

Customer data isn't being passed or stored in the session?

For some reason my code is not adding customer to the session. I am new to ASP.NET does anyone have any input as to why this is happening and maybe able to give some code example. Thanks!
Below it the code.
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
Second page of code below:
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("Customer"), 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
Protected Sub Clearbtn_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Clearbtn.Click
If Customer.Count > 0 Then
Customer.Clear()
lstCustomer.Items.Clear()
Else
clrErr.Text = "ERROR: NO CUSTOMERS STORED"
End If
End Sub
End Class
I think I've actually answered this in another of your questions
You need to add a line to actually store the updated customer object back into Session for example
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
Session("Customer") = customer
End Sub
Although I'd recommend you put this in another function so that your design doesn't depend on Session if you want to change it later on. So more like
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
StoreCustomer(customer)
End Sub
Private Sub StoreCustomer(ByVal customer As SortedList)
Session("Customer") = customer
End Sub
At the moment all local changes to customer are lost just after the call toto AddToCustomer as you then do a redirect after.
Me.AddToCustomer(customerItem)
Response.Redirect("CustomerList.aspx")

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.

Resources