asp.net server control not saving state properly - asp.net

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

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

Strange behaviour of ASP.NET DataGrid ItemCommand event

I use a DataGrid only programmatically.
Public Class MyOwnDataGrid
Inherits MyBaseClass
Private DataControl As New WebControls.DataGrid
Public Property DataSource as DataTable = Nothing
Public Sub New()
AddHandler Me.DataControl.ItemCommand, AddressOf Me.DataGrid_ItemCommand
Me.DataControl.AutoGenerateColumns = False
End Sub
End Class
On Page_Load I bind the DataSource and add the columns.
Protected Overrides Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
'I have to hold the DataSource in a Session variable because after PostBack is the DataSource property nothing
If (Not (Me.DataSource Is Nothing) And Not (Me.IsPostBack)) Then Session("DataSource") = Me.DataSource
If (Not (Session(Me.DataSourceSessionName) Is Nothing)) Then
Me.DataControl.DataSource = Session("DataSource")
Me.DataControl.DataSource.AcceptChanges()
End If
'add the columns with content
'add the columns for Actions
Dim oColumn As New TemplateColumn
oColumn.ItemTemplate = New ActionColumn With {.Control = New WebControls.ImageButton With {.SkinID = "Edit", .ToolTip = "Edit", .CommandName = "Edit"}}
oColumn.EditItemTemplate = New ActionColumn With {.Control = New WebControls.ImageButton With {.SkinID = "Update", .ToolTip = "Apply", .CommandName = "Update"}}
oColumn.FooterTemplate = New ActionColumn With {.Control = New WebControls.ImageButton With {.SkinID = "Insert", .ToolTip = "Add", .CommandName = "Insert"}}
Me.DataControl.Columns.Add(oColumn)
oColumn = New TemplateColumn
oColumn.ItemTemplate = New ActionColumn With {.Control = New WebControls.ImageButton With {.SkinID = "Delete", .ToolTip = "Delete", .CommandName = "Delete"}}
oColumn.EditItemTemplate = New ActionColumn With {.Control = New WebControls.ImageButton With {.SkinID = "Cancel", .ToolTip = "Cancel", .CommandName = "Cancel"}}
Me.DataControl.Columns.Add(oColumn)
'Bind the DataSource at every PostBack because otherwise the DataSource is empty and the control will be hidden
Me.DataControl.DataBind()
End Sub
Private Class ActionColumn
Implements System.Web.UI.ITemplate
Public Property Control As WebControls.ImageButton = Nothing
Public Sub InstantiateIn(ByVal container As System.Web.UI.Control) Implements System.Web.UI.ITemplate.InstantiateIn
If (Not (Me.Control Is Nothing)) Then container.Controls.Add(Me.Control.Clone)
End Sub
End Class
My problem is that the ItemCommand event works randomly.
Private Sub DataGrid_ItemCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DataGridCommandEventArgs)
Select Case e.CommandName.ToUpper
Case "Edit".ToUpper
'do something
Case "Cancel".ToUpper
'do something
Case "Update".ToUpper
'do something
Case "Delete".ToUpper
'do something
Case Else
End Select
End Sub
If I push the Edit or Delete button it works fine. With the Edit button one row is set in Edit mode and if I push there a button a strange behaviour occur. The both Buttons Apply and Cancel are available. If I push them at the Apply button the Delete button will be used and if I push the Cancel button the ItemCommand event is not fired but the row is not anymore in edit mode.
Where is my mistake? What do i wrong, that this doesn't work correctly? If I would create the columns in markup it works fine. But not in my case with all on server side.
Thanks for any response.
I thing u can call bindGrid() method after check page.ispostback on page_load like this :
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack)
{
return;
}
BindGrid();
}
check this post.

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.

RiseEvent from usercontrol or communicate between usercontrols

I have problem with bubbleup event from my dynamic loaded ascx control (katalogbooklist.ascx) to it´s parent control (ViewAJBarnboksKatalog.ascx)
i need to fire/run sub uppdateraAndraModuler in the parent control when the event addMultiVotes_command fires in the chiled control.
is there any one who knows or have an idea on how to do this?
/
Andreas
(the code lives in a dotnetnuke cms modules, if that's any help)
Partial Class ViewAJBarnboksKatalog '<--------Partial codebehind file for ViewAJBarnboksKatalog.ascx
Protected Sub Page_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Init
.. code for adding for loading katalogbooklist.ascx dynamic...
Me.Controls.Add(..code.. add katalogbooklist.ascx ..) '
End Sub
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim t As Execkoden = New Execkoden()
AddHandler t.onAjeventtest, AddressOf Uppdateramod
End Sub
Public Sub Uppdateramod(sender As Object, e As ajeventArgs)
uppdateraAndraModuler()
End Sub
Public Sub uppdateraAndraModuler()
'..do some code
End Sub
End Class
Partial Class katalogenBookList '<--------Partial codebehind file for katalogbooklist.ascx
Protected Sub addMultiVotes_command(ByVal sender As Object, ByVal e As System.EventArgs)
'..more code...
Dim te As New Execkoden ' <----- i want to use the constructor to raise the event in class Execkoden can´t raiseevent directly it wont´t fire
'... more code...
End sub
End Class
Public Class ajeventArgs : Inherits EventArgs
Public Sub New()
End Sub
End Class
Public Delegate Sub Uppdatera(sender As Object, e As ajeventArgs)
Public Class Execkoden
Public Event onAjeventtest As Uppdatera
Public Sub New()
RaiseEvent onAjeventtest(Me, New ajeventArgs)
End Sub
End Class
Create an event handler in the child control, like this:
public event EventHandler DeleteButtonClick;
When a button is clicked in the child control, do this:
protected void DeleteClick(object sender, EventArgs e)
{
if (this.DeleteButtonClick != null)
this.DeleteButtonClick(sender, e);
}
And in your parent control, in the markup:
<UC:SomeUserControl ID="UserControl1" runat="server" OnDeleteButtonClick="UserControl1_DeleteClick" ...>
And in the code behind of the parent control:
protected void UserControl1_DeleteClick(object sender, EventArgs e)
{
//do something
}
I would suggest using the IMC or Inter Module Communication feature that's built in to DotNetNuke.

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