Trouble using response.redirect - asp.net

Hi and sorry for my poor english.
I have an Asp.net + Vb.Net application and here is an example of code illustrating my problem :
First I have Default.aspx page with 2 buttons, "Valid" and "Redirect"
Protected Sub butvalid_Click(sender As Object, e As EventArgs) Handles butvalid.Click
If (File.Exists(Server.MapPath("log.txt"))) Then
Dim lines() As String = IO.File.ReadAllLines(Server.MapPath("log.txt"))
Dim tmp As Integer = Convert.ToInt32(lines(lines.Length - 1))
tmp = tmp + 1
File.AppendAllText(Server.MapPath("log.txt"), Environment.NewLine & tmp.ToString)
Else
File.WriteAllText(Server.MapPath("log.txt"), "1")
End If
End Sub
Protected Sub Redirect_Click(sender As Object, e As EventArgs) Handles Redirect.Click
Response.Redirect("accueil.aspx")
End Sub
Valid button write into a txt file and Redirect is redirecting ...
Here is the page_load code of accueil.aspx :
Threading.Thread.Sleep(3000)
Response.Redirect("default.aspx")
The problem is when I click on Redirect button in Default.aspx page, the valid button remains accessible and user can click on Valid button.
How can I disable Valid button after Redirect click ?
Thanks in advance.

Place this in Page_OnLoad handler and fire at each postback to make sure it is bound. This will disable the button on the client side, and when the page load fires again after the click is and response to the server is done, the button will be enabled again.
Redirect.Attributes.Add("onclick", "javascript:"
+ butvalid.ClientID + ".disabled=true;"
+ Page.ClientScript.GetPostBackEventReference(Redirect, null));

Related

Crystal Report Object not refreshing after IsPostBack

This is my .Net 2 ASP.Net code that used to work when hosted on Win 2000 and IIS3.
'In Page_Load, if it's NOT a PostBack then remove the cached report object so the that code later is forced to rebuild it.
Under Win2000 and IIS3 when I clicked a link to load the Page fresh, in Page_Load it would call Session.Remove("ReportObject"), then in FillRptParams realise the Session("ReportObject") is Nothing and reload it.
I initially put all the Session code in to make sure that between Crystal Report page requests it wouldn't keep going to the DB, it would just pull the ReportObject from the session variable display the next page.
Now I've switched to Win 2003 and IIS6 I ALWAYS get the SAME report served up, even when clicking on the link as I used to which essentially causes IsPostBack to be false and remove the Session object.
I'm hoping it might some settings under IIS6 that can make it behave as it used to.
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
If Not Page.IsPostBack Then
Session.Remove("ReportObject")
End If
End Sub
Sub FillRptParams(ByVal snavcode As String, Optional ByVal CrystalOrPDForEXCEL As String = "")
If Not Session("ReportObject") Is Nothing Then
bReportCached = True
Else
bReportCached = False
End If
oSqlCmd = New SqlCommand
If bReportCached Then
orpt = Session("ReportObject")
Else
orpt = New rptUsageSummaryNew
oSqlCmd.CommandText = "HOSP_RPT_UsageAllSummary"
oDS = oDataAccess.GetReportDataSet(Session("Group"), oSqlCmd)
orpt.SetDataSource(oDS)
'Cache the report object so we don't have to load it again next time
Session.Remove("ReportObject")
Session.Add("ReportObject", orpt)
End If
End Sub
Move your code in the Page_init event, not in the page_load.
And suppress your "if postback code" when you have moved it .

page refresh detection code not working

I found a nice article on how to detect page refresh in this article: Detecting browser 'Refresh' from Code behind in C#, I tried to follow the code and use it in a web form application written in vb.net.
My problem is that when I refresh the page using the browser refresh button, the boolean IsPageRefresh, always remains false. So the code that I am trying to prevent from executing on page refresh, keeps getting executed.
Here is an example if my vb.net code including the converted code from the article:
Dim IsPageRefresh As Boolean = False
Protected Sub Account_reset_Load(sender As Object, e As EventArgs) Handles Me.Load
If Not IsPostBack Then
ViewState("ViewStateId") = System.Guid.NewGuid().ToString()
Session("SessionId") = ViewState("ViewStateId").ToString()
Else
If ViewState("ViewStateId").ToString() <> Session("SessionId").ToString() Then
IsPageRefresh = True
End If
Session("SessionId") = System.Guid.NewGuid().ToString()
ViewState("ViewStateId") = Session("SessionId").ToString()
End If
End Sub
Protected Sub Account_reset_LoadComplete(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.LoadComplete
If (Not Page.IsPostBack) Then
If Not IsPageRefresh Then
If Not String.IsNullOrEmpty(Request("key")) Then
If Not (Customer.SignInByResetKey(Request("key"))) Then
Customer.Messages.Add("Invalid password reset key", MessageType.Error)
FormsAuthentication.SignOut()
Functions.Redirect(SiteLink.ResetPassword)
Else
' Do Nothing
End If
Else
Functions.Redirect(SiteLink.ResetPassword)
End If
Else
'Do Nothing
End If
End If
End Sub
I would like to ask for help to try to identify where I possibly am making the mistake, or if there is a better method.
I saw many articles that show how to catch page refresh in code behind, but they use the PreRender method, and I cannot implement that solution due to how to website was built.
I hope I can get some positive feedback.
Many thanks.

ASP.NET confirm delete in a grid

I need to add a confirm delete action to a grid. the problem is the way the "Delete" link is rendered.
my grid is built in code behind in vb.net.
i have this
colDelete.AllowDelete = True
colDelete.Width = "100"
AddHandler CType(gridSavedForLater, Grid).DeleteCommand, AddressOf dgDeleteSelectedIncident
and the sub is the following
Sub dgDeleteSelectedIncident(ByVal sender As Object, ByVal e As GridRecordEventArgs)
Dim message As String = "Are you sure you want to delete this incident?"
Dim caption As String = "Confirm Delete"
Dim result = System.Windows.Forms.MessageBox.Show(message, caption, Windows.Forms.MessageBoxButtons.OKCancel, Windows.Forms.MessageBoxIcon.Warning)
'If (result = Windows.Forms.DialogResult.Cancel) Then
'Else
' MessageBox("Are you sure you want to delete this incident?")
'Get the VehicleId of the row whose Delete button was clicked
'Dim SelectedIncidentId As String = e.Record("IncidentId")
''Delete the record from the database
'objIncident = New Incidents(SelectedIncidentId, Session("userFullName"))
'objIncident.DeleteIncident()
''Rebind the DataGrid
LoadSavedForLater()
'' End If
End Sub
i need to add a javascript confirm dialog when this sub is called. i can do it with a windows form messagebox but that does not work on the server.
pleae help
joe
You cannot show a MessageBox in ASP.NET since it would be shown on the server. So you need a javascript confirm onclick of the delete button. Therefor you don't need to postback to the server first. You can attach the script on the initial load of the GridView.
A good place would be in RowDataBound of the GridView:
Private Sub GridView1_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridView1.RowDataBound
Select Case e.Row.RowType
Case DataControlRowType.DataRow
' if it's a custom button in a TemplateField '
Dim BtnDelete = DirectCast(e.Row.FindControl("BtnDelete"), Button)
BtnDelete.OnClientClick = "return confirm('Are you certain you want to delete?');"
' if it's an autogenerated delete-LinkButton: '
Dim LnkBtnDelete As LinkButton = DirectCast(e.Row.Cells(0).Controls(0), LinkButton)
LnkBtnDelete.OnClientClick = "return confirm('Are you certain you want to delete?');"
End Select
End Sub
As an alternative, a common method of notifying users in a web page of a status change (save, delete, update, etc.) is having an update element in your HTML. Basically, a label (or whatever) that you'll set with updates to the user.
"Your changes have been successfully saved." or "An error was encountered when trying to save your update.", for example. You can set the color red for an error or whatever your programming heart desires, stylistically.
I kind of like this approach as a pop-up always feels more like a WinForm thing to me. Either works, so I just thought I'd suggest another approach.

ASP button control firing

The problem im having is a little complicated to explain, so please bear with me. I have 2 button controls. In the page load, I wanted to know what button created a postback on the page load. Through research I have found this snippet below and it works as expected. So here is my scenario of events that occur when click on the button.
1. Click the button does a postback
2. Runs the function below and tell me the id of the button
3. Runs the clicked event handlers for that button
Protected Sub btnCalc_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnCalc.Click
' Do this
End Sub
The problem comes in when I click the second button, it does steps 1 and 2 but NEVER DOES 3. Through testing, I have that it only does 1, 2, and 3 on the first button clicked. I have no clue why this is happening?
Function GetPostBackControlName() As String
Dim control As Control = Nothing
Dim ctrlname As String = Page.Request.Params("__EVENTTARGET")
If ctrlname <> Nothing AndAlso ctrlname <> [String].Empty Then
control = Page.FindControl(ctrlname)
Else
Dim ctrlStr As String = [String].Empty
Dim c As Control = Nothing
For Each ctl As String In Page.Request.Form
c = Page.FindControl(ctl)
If TypeOf c Is System.Web.UI.WebControls.Button Then
control = c
Exit For
End If
Next
End If
Try
Return control.ID.ToString
Catch
Return ""
End Try
End Function
You really should look into just assigning Click event handlers to your buttons. Asp.net was designed purposely so that you wouldn't have to parse through the request object like you are doing above.

How to call Value from web form?

I creat one WEB project, this project contain tow WEB FORM, In the first Web Form Design i have tow TextBox for Entring the date(All dataTable between this tow dates) and one Button, I want that when i press to to this Button it will load the second WEB FORM and show all the Data Table in DataGrid In this WEB FORM, So i need To call this tow TextBox value from the first WEB FORM to the second WEB FORM In Load_Page i will use this tow value in select statment. So i want to know how to call this to value from the first WEB FORM. I'am using VB.NET WEB APPLICATION.i have allrady DB in SQL .
you have a lot of ways to pass values from page to another like query string, sessions, etc....
Another way to achieve this is by using the PostBackUrl property of the button.
Refer Button..::.PostBackUrl Property for more information
You can use querystring to get last page values to load page. Use this code
Response.Redirect("Default.aspx?value1 =" & value & "&value2" & value)
write page name as like default.aspx.
In the button click on the first page, you can call the second page by using Server.Transfer like this:
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs)
TextBox1.Text = TextBox1.Text & " Add something before continue..."
Server.Transfer("SecondPage.aspx")
End Sub
Then you can get the textbox from the first page in the second page Page_load event:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
Dim lastPage As Page = Context.Handler
Dim textBox As TextBox = lastPage.FindControl("TextBox1")
End Sub
If you don't need to do anything on the button event other than posting to the next page, you can do it simpler...
Definition of the button in the ASPX markup for the first page:
<asp:Button id="Button1" PostBackUrl="SecondPage.aspx" Text="Continue" runat="Server"/>
Then you can get the textbox from the first page in the second page Page_load event:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
Dim textBox As TextBox = PreviousPage.FindControl("TextBox1")
End Sub

Resources