I have a custom control that inherits from .NET's CompositeControl class. This control overrides the CreateChildControls in order to build its child controls dynamically. I need the page to post back after a couple different javascript events occur on the client side.
In order to accomplish this, I create two hidden controls on the page so I can set their values with javascript, submit the page, and read the values out on server side. Here's is the code I use to create these two hiddens:
Protected Overrides Sub CreateChildControls()
hdEventName = New HiddenField()
Controls.Add(hdEventName)
hdEventName.ID = "hdEventName"
hdEventArgs = New HiddenField()
Controls.Add(hdEventArgs)
hdEventArgs.ID = "hdEventValue"
' other controls
' ...
End Sub
When a javascript event occurs I set the value attribute of the two hiddens and submit the page, like so:
hdEventName.value = 'EventName';
hdEventArgs.value = 'arg1,arg2';
document.forms[0].submit();
In the OnLoad method of my control, I attempt to check the Value property of the hdEventName and hdEventArgs controls, but it is always empty. However, Page.Request.Form(hdEventName.UniqueID) and Page.Request.Form(hdEventArgs.UniqueID) return correct values. The actual HTML in the markup also shows correct values after the page posts back.
Why is the Value property of the HtmlInputHiddens disconnected from the actual value that appears on the client?
Update
It appears that a control's properties get loaded from the form sometime after OnLoad occurs. Thus I was able to solve my problem by either moving the code that checks the two hidden fields into the OnPreRender method, or adding the following method to my code -
Private Sub Event_Handler(ByVal sender As Object, ByVal e As EventArgs)
Handles hdEventName.ValueChanged
' do stuff with hiddens
' ...
' reset the values back
hdEventName.Value = String.Empty
hdEventArgs.Value = String.Empty
End Sub
when the page posts back there's nothing to link the variable hdEventName to the control you previously created. what you're doing is akin to having an integer declared at the class level and setting it to 5 when you're creating child controls. there's nothing to maintain that value in that variable across postbacks.
if you want to get a reference to the control you created previously, you'd have to use
hdEventName = CType(Page.FindControl("hdEventName") , HiddenField)
(i'm guessing at this) or Request if you're only concerned with the value.
It appears that a control's properties get loaded from the form sometime after OnLoad occurs. Thus I was able to solve my problem by either moving the code that checks the two hidden fields into the OnPreRender method, or adding the following method to my code -
Private Sub Event_Handler(ByVal sender As Object, ByVal e As EventArgs)
Handles hdEventName.ValueChanged
' do stuff with hiddens
' ...
' reset the values back
hdEventName.Value = String.Empty
hdEventArgs.Value = String.Empty
End Sub
Related
Using vb.net 4.5 and Telerik 2017.2.711.45 (Q2)
I am trying to get radgrid filter expressions and a public string variable to persist across postbacks.
With EnableViewState=FALSE, radgrid filter expressions do not persist through postback, however a public string variable (stringVar) does persist.
When I set EnableViewState=TRUE the filter expressions in radgrid do persist, however it causes stringVar to not persist.
From my understanding of ViewState, it makes no sense that setting EnableViewState=TRUE would cause stringVar to not persist across postbacks. I would love to know why this is occurring and what I could do to resolve this.
EDIT:
The highlighted Line is where an error would be thrown because ReportTitle no longer has a value.
Partial Class displayxslgrid
Public ReportTitle As String
Public ReportsDB As reportDataBase
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Page.EnableViewState = True
Reports = New reportDataBase.Global_Functions(System.Web.HttpContext.Current)
End Sub
Protected Sub RadGrid1_NeedDataSource(sender As Object, e As Telerik.Web.UI.GridNeedDataSourceEventArgs) Handles RadGrid1.NeedDataSource
Call BindRadGrid1()
End Sub
Protected Sub RadGrid1_ItemCommand(ByVal source As Object, ByVal e As Telerik.Web.UI.GridCommandEventArgs) Handles RadGrid1.ItemCommand
Dim strReportTitle As String
Select Case e.CommandName
Case RadGrid.ExportToExcelCommandName, RadGrid.ExportToWordCommandName, RadGrid.ExportToCsvCommandName
strReportTitle = ReportTitle.Trim
End Select
End Sub
Public Sub BindRadGrid1()
Dim strReportTitle As String
Dim dt As DataTable = Nothing
ReportTitle = dt.Rows(0).Item("ReportTitle")
strReportTitle = dt.Rows(0).Item("ReportTitle").ToString
'RadGrid1 Data source gets set here along with other stuff
End Sub
End Class
Using view state is normal, and Telerik controls need it to preserve their values across post-backs. A public string property on your page class should not persist, and should be set/calculated every time. If you absolutely need something like that to persist, save the value in a hidden server control, or have it in the QueryString of the URL.
So it turns out, that that variable was not truly persisting. It was getting its value from the bindradgrid1. When EnableViewState=True the need data source event is not fired, therefore the bindradgrid1 is not called and the variable does not get a value. Simple fix was adding a bindradgrid1() in the item command sub so that even with EnableViewState=True, bindradgrid1() will still get called. Thanks for all who helped.
I am looking for a way, that knowing a controls name, to raise them or call the processes event/code behind.
I am using VB .NET in VS2010
I have an aspx page with a selection of checkboxes in a panel, each checkbox has its own trigger. I have code that saves a list of checked checkboxes. I have code that restores the checked states to those checkboxes, but I need to execute the associated code to the checkboxes checkchanged event.
' Read db to get saved list of checkboxes '
For each result from db
Dim cb As CheckBox
cb = 'a function that finds and returns the control'
' Now that I have the control,
' how can I find and execute it's checkedchanged code?
The control return function is working because in testing, I can process cb.checked = true, and the cb becomes checked, but this doesn't raise the event/trigger the code.
Example of associated checkedchanged subs:
Protected Sub cb_use_rc3_CheckedChanged(ByVal sender As Object, ByVal e As EventArgs) Handles cb_use_rc3.CheckedChanged
Protected Sub cb_use_casestatus_CheckedChanged(sender As Object, e As EventArgs) Handles cb_use_casestatus.CheckedChanged
Any ideas?
For Each grd_Row As GridViewRow In gvPersonalInventario.Rows
Dim cb As New Web.UI.WebControls.CheckBox
cb = grd_Row.FindControl("CheckBox2")
If cb.Checked = True Then
label1.text = grd_Row.Cells(0).Text
End If
Next
OK, I'm working on the assumption that your checkboxes each have an individual ID and are not generated by a bound control of any sort.
While it is possible to determine what handler is hooked up to what event of what object (or so I understand), it's probably more trouble than it's worth for this limited case.
The simplest, though ugliest, way to do it would be this:
Follow Mr. Schmelter's advice and isolate the business logic in meaningfully-named methods. Call them from each event handler rather than putting all the logic in the event handler.
Since you have the control, you can determine its ID. Use a Select Case statement with the ID of the control to determine which method or methods from #1 to call.
I have a master page and a user control
I have written an event in usercontrol and i want to call that event in my master page.
following are my codes
masterpage ----------- ( I THINK THIS PART IS CORRECT, IT'S DOING WHAT IT IS SUPPOSE TO DO;CALLING THE USER CONTROL FUNCTION. )
Dim App_Cl_tpPerson As New App_Cl_tpPerson
App_Cl_tpPerson.PersonAdd_Click(sender, e)
usercontrol page ---------- ( I FEEL THE PROBLEM IS HERE )
Public Sub PersonAdd_Click(ByVal sender As Object, ByVal e As EventArgs)
Try
If Req_No = 0 Then
Req_No = Convert.ToInt32(Request.QueryString("reqID"))
End If
Catch ex As Exception
End Try
End Sub
The error message is "OBJECT REFERENCE NOT SET TO AN INSTANCE OF AN OBJECT"
.
If you have created a control in your master page, you need to place an event handler there as well. The reason you are getting the error is because the master page's control is looking for the event handler in the master page's class and there is none defined.
Since all you are doing is getting the QueryString value, which the master page has access to, you can accomplish what you want by simply moving the method from your derived page to your master page.
Then, since you need the Req_No value to be accessible to your templated page, you must add a public property or method to your master page to allow your templated page to access the value.
Finally, to use your property/method call in your templated page, you would do the following:
Public Sub DoSomething()
Dim Req_No As Integer = CType(Me.Master, MyMasterClassName).Req_NoProperty
End Sub
(Note, I don't use VB all that often, so I'm not sure if the CType call would work, but the general idea is you need to cast the Page class' reference to the Master Page to your specific Master Page's class since that is where the property or method you wrote resides).
Based on a choice of "Other" in a dropdown I want to add a label and textbox to a <p> tag. I have added runat=server in the <p> tag.
Protected Sub deptDdl_SelectedIndexChanged(sender As Object, e As System.EventArgs) Handles deptDdl.SelectedIndexChanged
'If the user chooses other for the department type add
'a label and textbox to allow them to fill in a department not listed
If deptDdl.SelectedValue.ToString = "Other" Then
Dim deptLbl As Label = New Label
deptLbl.Text = "Enter the Department Name"
Dim deptTb As TextBox = New TextBox
deptTb.MaxLength = 20
Page.FindControl("m_ContentPlaceHolder1_deptPtag").Controls.AddAt(2, deptLbl)
Page.FindControl("m_ContentPlaceHolder1_deptPtag").Controls.AddAt(3, deptTb)
End If
End Sub
I keep getting an unhandled exception stating Object reference not set to an instance of an object.
What am I missing?
If your <p>-tag is runat=server you should be able to reference it in the codebehind -file directly. Give it an ID deptPtag, then this should be autogenerated in the designer.vb-file:
Protected WithEvents deptPtag As Global.System.Web.UI.HtmlControls.HtmlGenericControl
But you also have to ensure that your dynamic controls are recreated on every postback(latest in Page_Load, events are too late for reloading the ViewState). Otherwise you won't be able to read deptTb.Text or handle it's TextChanged-event.
The ID must be the same on every postback to correctly load the ViewState.
My answer on this question explains your NullReferenceException.
It's a special behaviour of FindControl from within a MasterPage's content-page.
Hey all, i am new at everything VB.net/ASP.net so i need some help with a problem i am currently having.
I have an ASCX.vb page that lets the user choose someone from a table. Once they do select someone, the page reloads with that persons information into another table below that one where they can submit an order for that person or remove that person.
Problem being is that i wanted to store the users ID that are selected but it seems that everytime the page reloads to show an update, it dim's my array again back to default.
This is my code once they choose a user:
Namespace prog.Controls
Partial Public Class progReportGrid
etc....
Public strIDArray() As String = {"0000770000"} 'Just a dummy place holder
Private Sub gvData_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles gvData.RowCommand
Dim idIndexNumber As Integer = Array.IndexOf(strIDArray, strID)
For i As Integer = 0 To strIDArray.Length - 1
System.Diagnostics.Debug.WriteLine(strIDArray(i))
Next
If idIndexNumber = -1 Then
ReDim Preserve strIDArray(strIDArray.Length)
strIDArray(strIDArray.Length) = strID
RaiseEvent EmployeeSelected(Me, New ESEventArgs(strID))
End If
End Sub
So everytime to page reloads the Public strIDArray() As String = {"0000770000"} gets called again and, of course, clears anything that was saved to it other than 0000770000.
How can i keep it from doing this?
UPDATE
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not Page.IsPostBack Then
'do what?
End If
End Sub
David
Perhaps you have a misunderstanding with the stateless model of a web application. Anything that is not stored in the ViewState or Session or a shared application variable will NOT persist through postbacks.
This means that when you declare your
Public strIDArray() As String
as a standard variable, it will be re initialized every time the page posts back.
For example, here's a simple flow of how this works:
The user opens their browser and opens up your aspx web page.
The request goes to your server, and all the controls including progReportGrid are instantiated as new instances and added to the page. (this is where your variable gets set to its original value every time)
A bunch of events are fired, including the Me.Load event
Controls that were added to the page are asked to generate their HTML
The HTML gathered from all the controls on the page is sent back to the user
So because your controls are all re-instantiated every post back, class variables like strIDArray are pretty much thrown out after the page is sent to the user.
Instead, if you want the page to remember what value the array had last postback and add more to it next postback, you have to use either ViewState, or Session.
For example:
Private Property StrIDArray() As String()
Get
If ViewState("StrIDArray") Is Nothing
ViewState("StrIDArray") = New String() {"0000770000"}
Return ViewState("StrIDArray")
End Get
Set(ByVal value As String())
ViewState("StrIDArray") = value
End Set
End Property
Now if you used this property instead of your variable, you could manipulate that array and as long as the user is on that page, the value of that array will persist across postbacks.
Use the Page.IsPostBack property in your Page_Load method.
This property is false for the first time the page loads and false for every postback afterwards.
If you set your default value strIDArray() = {"0000770000"} within If (Page.IsPostBack <> true) then it will not get reset on the postback.
EDIT : My VB syntax is VERY shaky but let me try it out
Partial Public Class EARNReportGrid
Begin
Public strIDArray() As String // DO NOT INITIALIZE it here. ONLY DECLARE IT
.....
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not Page.IsPostBack Then
//INITIALIZE the ARRAY
strIDArray = New String(){"00007700000"}
End If
End Sub
......
End