Transfer radio button from webform to another form using VB.net and ASP.net - asp.net

I wrote the below code which transfer the radio button value and check box value to another HTML form but i did not find solution to transfer the radio button or check box at all to another form not only the selected value.
I want the radio button to be transfered to another form as below not only the value.
enter image description here
Dim Gender As String = RadioButton1.SelectedValue
Response.Redirect("PrintPreview.aspx?"&Gender=" + Gender)
Label1.Text = Request.QueryString("Gender")
The code only returned the radio button value
Please advise

Ok, the FIRST thing, and MOST important thing to realize here is that when you execute a response.Redirect ?
It STOPS code running in the current page.
No code AFTER the Response.Redirect will run
All variables, and code and ALL values for the current page are destroyed!
So, you can't write (normally) code to run after the response.Redirect.
So, say we have this markup:
<br />
<asp:RadioButtonList ID="RadioButtonList1" runat="server"
Font-Size="Larger" RepeatDirection="Horizontal">
<asp:ListItem>Yes</asp:ListItem>
<asp:ListItem>No</asp:ListItem>
</asp:RadioButtonList>
<br />
<asp:Button ID="Button1" runat="server" Text="Done" />
And our page now looks like this:
Now, we want to jump to page 2.
So our code can say look like this in our Test1 page.
Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim Gender As String = RadioButtonList1.SelectedItem.Text
Response.Redirect("Test2.aspx?&Gender=" & Gender)
' code AFTER above line WILL NOT run!!!!
End Sub
So, we can't have code AFTER the response.Redirect.
Again, read this 5 times:
when the response.Redirect is used, then the current page code STOPS,
and ALL values, and even your code variables are DESTROYED!!! This is not much
different then when you get to the end of a subroutine - when you exit, then all
values and things in that subroutine are "gone", and "do not exist".
The same goes for your web page - using Response.Redirect means STOP code, transfer to another page.
So, now above will jump to page Test2, we want to take that value we passed, and do this:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
' save a label on this page to the passed choice
Label1.Text = Request.QueryString("Gender")
End If
End Sub
Also, note close your syntax for the string you were passing in Response.Redirect was also incorrect.

Related

asp:textbox calling asp:button handler on text change

I have the most bizarre problem happening ... I'm controlling a menu edit page and I have a series of controls, an asp:textbox with the numeric ID of the menu being worked on, flanked by - and + buttons to decrement and increment the ID. The user can type a new index in the textbox, or use the buttons. Easy peasy, right?
Here's the ASPX markup:
<asp:Button id="menuDown" runat="server" CausesValidation="false" OnClick="DownClick" Text="-" />
Menu # <asp:textbox runat="server" MaxLength="5" Columns="3" id="tbMenuId" />
<asp:Button id="menuUp" runat="server" CausesValidation="false" OnClick="UpClick" Text="+" />
There's a CompareValidator further down the page ensuring a non-negative, numeric entry.
Over in my code behind, my Page_Load pulls the value out of the textbox without problems:
Try
menuId = Integer.Parse(tbMenuId.Text)
Catch
menuId = 0
tbMenuId.Text = "0"
End Try
This works great (with ONE caveat) — every time I change the menu ID via the textbox, after the Page_Load method pulls the new value out of the text box perfectly, the DownClick handler gets called, decrementing the desired ID.
So far, the ONLY way I've managed to have the requested menu appear is to eliminate the two asp:Button controls. Eliminating only the menuDown button causes the UpClick handler to get called.
I had an OnTextChanged="..." attribute on the asp:Textbox control, but that handler NEVER got called and didn't seem necessary anyway, so I pulled it.
I cannot help but think the two behaviors must be connected.
Anyone understand WHY this is happening?
This qualifies as hacky work-around, rather than a fix, but it does let me proceed forward until this behavior can be explained.
The OnTextChanged event is firing the way it's supposed to now (not sure what I did wrong the first time) so, I used it to implement the hackiest of hacks ...
Protected Property hackyFlag As Boolean ' Suppress button click (true) after text change
' ... value in session variable
Protected Sub tbMenuId_TextChanged(sender As Object, e As EventArgs)
Integer.TryParse(tbMenuId.Text, menuId)
hackyFlag = True
End Sub
Protected Sub DownClick(sender As Object, e As EventArgs)
If hackyFlag Then : hackyFlag = False : Return : End If
If menuId > 0 Then menuId -= 1
tbMenuId.Text = menuId
End Sub
Gross, hacky, and disgusting ... but it works. :-) The button handler is still being called incorrectly, but now it's smart enough to do what I want instead of what the framework is telling it to do.
Still open to better answers and/or explanations as to why this is happening on this page and hasn't happened on any other. ( knock on wood )

Using a Timer to Update a Label in an ASP.Net Web Application

I have a label on my master page that I would like to see update every second, keeping track of the seconds elapsed. I have revised my question and have seen some progress but have a new problem.
I have restructured my code to include an ASP:Timer, Trigger, and AsyncPostBackTrigger (all wrapped within an UpdatePanel) but the update only seems to happen once... The default label text appears, is updated to "1" and then stays that way even though the back-end code continues to count upwards.
Back End:
Public intCounter As Integer = 0
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
getUserAccess()
manageAccess()
End Sub
Protected Sub testTimer_Tick(ByVal sender As Object, ByVal e As System.EventArgs) Handles testTimer.Tick
intCounter += 1
lblTestTimer.Text = intCounter
End Sub
HTML:
<div>
<asp:Timer ID="testTimer" OnTick="testTimer_Tick" runat="server" Interval="1000"></asp:Timer>
</div>
<asp:UpdatePanel runat="server">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="testTimer" EventName="Tick"/>
</Triggers>
<ContentTemplate>
<asp:Label ID="lblTestTimer" CssClass="ticketLabel" Text="Ticket Alert!" runat="server"></asp:Label>
</ContentTemplate>
</asp:UpdatePanel>
Final Issue (Fixed): My interval was being reset on each page load, I changed the declaration to Shared and all is well. Thank you to #the_lotus for the help!
You should really read about page life cycle. The server can't connect to the client like that. Usually, the timer is done on the client using javascript and call the server for the updated value. It's not like a winform where everything is run on the client.
Since you are using an UpdatePanel, you could probably use the asp:Timer to run a timer on the client.
Your variable also gets reset on every page load. Save the value in a session or make it shared.

ASP.NET - Two User Controls - Multiple Instances Added at Runtime

I have a VB ASP.NET web application with two User Controls each containing one text input. There are two submit buttons each corresponding to one of the User Controls.
Clicking a button adds an instance of its corresponding User Control. For the most part this works except that in a specific scenario the IDs of the textboxes get mixed up thereby mixing up previously entered values.
The problem scenario is as follows:
1) Click the second button (the Add Approver button) twice and enter some values in the two resulting textboxes (for ease of analysis make the values different).
2) Click the first button (the Add Document button) once. (There is no need to add any value in the resulting textbox here.)
At this point everything appears correct. Viewing the page source, I see that the two "Approver" textboxes have IDs of ctl02_txtApprover and ctl03_txtApprover and the one "Document" textbox has an ID of ctl04_txtDocument.
Click the first button (the Add Document button) again.
At this point the value in the first "Approver" textbox disappears. The value in the second "Approver" textbox migrates to the first "Approver" textbox. Viewing the page source, the IDs for the two "Approver" textboxes have changed to ctl03_txtApprover and ctl04_txtApprover. The migrated values make sense considering that the textbox IDs have changed. In other words, the ViewState appears correct but the control IDs are incorrect.
I have made the code as simple as I can and have posted it here.
Default.aspx
<%# Page Language="vb" AutoEventWireup="false" CodeBehind="Default.aspx.vb" Inherits="WebApplicationUserControlTest._Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<asp:PlaceHolder ID="phDocument" runat="server" />
<asp:Button ID="btnAddDocument" runat="server" Text="Add Document" />
<br /><br />
<asp:PlaceHolder ID="phApprover" runat="server" />
<asp:Button ID="btnAddApprover" runat="server" Text="Add Approver" />
</form>
</body>
</html>
Default.aspx.vb
Public Class _Default
Inherits System.Web.UI.Page
Private Const VIEWSTATE_DOCUMENT_COUNT As String = "DocumentCount"
Private Const VIEWSTATE_APPROVER_COUNT As String = "ApproverCount"
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
ViewState(VIEWSTATE_DOCUMENT_COUNT) = 0
ViewState(VIEWSTATE_APPROVER_COUNT) = 0
Else
're-display any preexisting dynamic sections on postback
AddAllDocumentInfoSections()
AddAllApproverSections()
End If
End Sub
Protected Sub btnAddDocument_Click(sender As Object, e As EventArgs) Handles btnAddDocument.Click
ViewState(VIEWSTATE_DOCUMENT_COUNT) += 1
AddDocumentSection()
End Sub
Protected Sub btnAddApprover_Click(sender As Object, e As EventArgs) Handles btnAddApprover.Click
ViewState(VIEWSTATE_APPROVER_COUNT) += 1
AddApproverSection()
End Sub
Private Sub AddAllDocumentInfoSections()
For i As Integer = 0 To ViewState(VIEWSTATE_DOCUMENT_COUNT) - 1
AddDocumentSection()
Next
End Sub
Private Sub AddAllApproverSections()
For i As Integer = 0 To ViewState(VIEWSTATE_APPROVER_COUNT) - 1
AddApproverSection()
Next
End Sub
Private Sub AddDocumentSection()
Dim c As UserControl = LoadControl("~/Document.ascx")
phDocument.Controls.Add(c)
End Sub
Private Sub AddApproverSection()
Dim c As UserControl = LoadControl("~/Approver.ascx")
phApprover.Controls.Add(c)
End Sub
End Class
Document.ascx
<%# Control Language="vb" AutoEventWireup="false" CodeBehind="Document.ascx.vb" Inherits="WebApplicationUserControlTest.Document" %><asp:TextBox ID="txtDocument" runat="server" /><br /><br />
Approver.ascx
<%# Control Language="vb" AutoEventWireup="false" CodeBehind="Approver.ascx.vb" Inherits="WebApplicationUserControlTest.Approver" %><asp:TextBox ID="txtApprover" runat="server" /><br /><br />
I am using Visual Studio 2010. The Target Framework is 4.0. I have tried changing the clientIDMode but this does not seem to make a difference. Have I run into a bug with .NET or is there something wrong with my code?
There is something wrong with your code.
If you dynamically add controls to the same naming container in a control tree, then you need to add them in the same order after each postback.
In your case, you're not doing this.
At your step 2, you have added three controls in this order:
Approver 1 (AddAllApproverSections)
Approver 2 (AddAllApproverSections)
DocumentInfo 1 (btnAddDocument_Click)
But then after the postback, you regenerate them in the following order:
DocumentInfo 1 (AddAllDocumentInfoSections)
Approver 1 (AddAllApproverSections)
Approver 2 (AddAllApproverSections)
Hence the control ids aren't the same, and the problems you're seeing.
One solution might be to store additional information in ViewState that represents the order the controls were added, so that you can recreate them in the same order.
But I'd probably be inclined to go for a different approach, for example put the DocumentInfo sections into the template of a Repeater, and the Approver sections into a second Repeater. Each Repeater would be data bound to a suitable collection, and adding an item (Approver or DocumentInfo) would be achieved by adding an element to the relevant collection and calling DataBind.
The problem here is that you are modifying the Controls collection and ViewState after they have been initialized. You should never dynamically add controls in the Page Load event.
You need to add your controls in the Page_Init stage of the Page life cycle, and remove the code from the else statement in your Page_Load event. Your new Page_Init event would look like this:
Protected Sub Page_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Init
AddAllDocumentInfoSections()
AddAllApproverSections()
End Sub
I believe you may have to change the way you're storing the "count" for these controls, as the View State information is not yet available at this stage. I would just store it as a Session variable, in that case. You'd just need to change your reference to "ViewState" throughout that code sample with "Session", like this:
Private Sub AddAllDocumentInfoSections()
For i As Integer = 0 To Session(VIEWSTATE_DOCUMENT_COUNT) - 1
AddDocumentSection()
Next
End Sub

Cache Object and Commit on Page Load

What we want to do is save an entire control into Cache and recommit the properties on page load, including data items. But we'd like the controls to exist already in the page.
Is this possible?
<html>
<asp:Repeater runat="server" id="rptListOfSubscribers">
<ItemTemplate>
<%# Eval("Name")%><br />
</ItemTemplate>
</asp:Repeater>
</html>
VB:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
If Cache("MyRepeater") Is Nothing Then
Dim rpt As Repeater = InitaliseRepeater()
Cache.Insert("MyRepeater"), rpt, Nothing, DateTime.Now.AddMinutes(720), Tim
eSpan.Zero)
End If
rptListOfSubscribers = Cache("MyRepeater")
End Sub
Function InitaliseRepeater() As Repeater
Dim rpt As New Repeater
rpt.DataSource = x
rpt.DataBind()
Return rpt
End Function
Excuse the short-hand code.
Yes that is possible the cache will take any object including a webcontrol. However probably best to do it earlier than Page_Load -Page_init perhaps.
Also I am curious as to your reasons behind doing this .. It seems like an awful solution. Also when you add the control to the page again when the viewstate page cycle methods run it will potentially change the control instance you have...
Can you describe the problem you are trying to solve with the cached web control?

Events Firing Out Of Order Asp.Net

I have a system setup as follows:
User Control Called "Main" when I click a button in "Main" another user control (user control "A", user control "B", user control "C") is populated inside a placeholder of "Main" depending on some logic either A,B, or C is populated.
User controls A,B,C have many buttons on them as well. They Also have a placeholder to contain either user control x, user control y, user control z depending what is clicked inside user control "A" for example.
Main loads controls (A,B, or C) into its placeholder no problem, but when I click a button in A,B,or C to load their placeholder with x,y, or z the whole control (A,B, or C) dissappears.
I understand this has to do with viewstate not holding dynamic controls during a postback. So what I did was explictly called viewstate on the controls loaded into main (A,B,C). when they are loaded I save an entry of what was loaded like this ViewState("lastLoaded")='A' for example. When a postabck occurs (i.e. clicking a button in A) I reload the whole control A.
This is what happens:
I click a button in user control "A"
Postback occurs
User control "A" is reloaded because of the viewstate("lastloaded")
Then I have to click the button in "A" again at that time the button_click event fires
Can someone please help me fix this.
'Here is Main.ascx
Partial Class Main
Inherits System.Web.UI.UserControl
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
ViewState("name") = "ControlA2.ascx"
AddControl(ViewState("name").ToString())
End Sub
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If ViewState("name") <> String.Empty Then
AddControl(ViewState("name").ToString())
End If
End Sub
Public Sub AddControl(ByVal name As String)
PlaceHolder1.Controls.Clear()
Dim toAdd As Control = LoadControl(name)
PlaceHolder1.Controls.Add(toAdd)
End Sub
Protected Sub Button2_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button2.Click
ViewState("name") = "ControlB.ascx"
AddControl(ViewState("name").ToString())
End Sub
End Class
'Here is Main designer
Main
asp:Button ID="Button1" runat="server" Text="Add Control A"
asp:Button ID="Button2" runat="server" Text="Add Control B"
asp:PlaceHolder ID="PlaceHolder1" runat="server">
'Here is ControlA2.ascx
Partial Class ControlA2
Inherits System.Web.UI.UserControl
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
PlaceHolder1.Controls.Clear()
Dim toAdd As Control = LoadControl("ControlX.ascx")
PlaceHolder1.Controls.Add(toAdd)
End Sub
End Class
'Here is ControlA2 designer
I am Control A
Add Control X
asp:Button ID="Button1" runat="server" Text="Add Control X"
asp:PlaceHolder ID="PlaceHolder1" runat="server"
/asp:PlaceHolder
'Here is ControlB.ascx
Partial Class ControlA2
Inherits System.Web.UI.UserControl
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
PlaceHolder1.Controls.Clear()
Dim toAdd As Control = LoadControl("ControlZ.ascx")
PlaceHolder1.Controls.Add(toAdd)
End Sub
End Class
'Here is ControlB designer
I am Control B
Add Control Z
asp:Button ID="Button1" runat="server" Text="Add Control Z"
asp:PlaceHolder ID="PlaceHolder1" runat="server" /asp:PlaceHolder
'Here is ControlX.designer
asp:Label ID="Label1" runat="server" Text="Label">I AM CONTROL X /asp:Label
'Here is ControlZ designer
asp:Label ID="Label1" runat="server" Text="Label">I AM CONTROL Z /asp:Label
I've created a project based on your code and I've managed to recreate the issue.
When I initially run it and click on the Add control A button the Main control will load Control A and note this in the viewstate. Control A's button to add Control X will now appear with an id of Main1_ctl00_Button1. When clicking on this button Main's page load will add Control A back to it's placeholder and Control A's button click event will fire. If you now click Main's Control A button again the problem arises. Main's page load method will look at the Viewstate and add control A to the placeholder. Then Main's button click event will then fire clearing the placeholder and re-adding control A. When the form is displayed Control A's button to add Control X will now have an id of Main1_ctl01_Button1 as it was the second control to be generated in the code behind. Now when you click on the button to add control x Main's page load will add Control A again but as it's id will be Main1_ctl00_Button1 and the click event came from a button with an id of Main1_ctl01_Button1 the event will not fire.
To fix this you will have to avoid the duplication of control creation the second time around. You could do this by checking the requests form collection during the page load to see which button was pressed although this is not a very elegant solution. You will need to ensure that the buttons on the Main control have a unique text value for this to work.
Hopefully someone else may be able to come up with a more elegant solution:
Dim mainButtonClick = False
For index As Integer = 0 To Request.Form.Count
If Request.Form(index) = "Button A" Or Request.Form(index) = "Button B" Then
mainButtonClick = True
End If
Next
If Not IsPostBack And Not mainButtonClick And ViewState("name") <> String.Empty Then
AddControl(ViewState("name").ToString())
End If
Please excuse any errors in this code as I am not a VB.NET programmer.

Resources