I have 2 button controls. When I click one i'm trying to determine which one caused a postback in the page load. How to do determine this?
What about using CommandName and CommandArgument has shown in this example. This way you can have just one handler.
<asp:Button id="Button1"
Text="Sort Ascending"
CommandName="Sort"
CommandArgument="Ascending"
OnCommand="CommandBtn_Click"
runat="server"/>
<asp:Button id="Button2"
Text="Sort Descending"
CommandName="Sort"
CommandArgument="Descending"
OnCommand="CommandBtn_Click"
runat="server"/>
Do you come from a Classic ASP background? When I first used ASP.NET, the same question occurred to me.
Consider an alternative approach:
Rather than detect the postback in the Form_Load, and then figure out what triggered it, create a specific event handler for each of your buttons. This is the whole point of Web Forms - so you can develop apps in very similar ways as you would Windows applications.
Really input with type button sends its value within post request. For example if you have you'll get in Post button-name=Quote like it's simple text input. So you can just check if post contains value for the button using code like following (sorry for my vb):
Dim isQuote As Boolean = HttpContext.Current.Request.Form(SubmitQuote.UniqueID) IsNot Nothing
so if it's not Nothing (null) then post has been sent by SubmitQuote button.
BTW for me HttpContext.Current.Request("__EVENTTARGET") didn't work either.
In my implementation there are several forms on my page; if a post-back was triggered by certain button controls further operations are necessary.
The controls are of the following type, which do not populate Request["__EVENTTARGET"]
Button (at the root of the form)
Image Button (nested within a Datagrid)
I determine if the following button controls instigated the post-back, by reviewing that the UniqueID of the control was passed to the form request within the Page_Load sub:
- ASP.NET:
<asp:Button ID="Button1" runat="server" />
<asp:Button ID="Button2" runat="server" />
To simply handle whether the following nested image button instigated the post-back I take advantage of the OnClientClick attribute which calls to a javascript function that will populate the value of a supplementary hidden field control with the UniqueID of the instigating control, then review the hidden control value similarly in the Page_Lode sub:
- ASP.NET:
<script type="text/javascript">
function SetSource(SourceID) {
var hiddenField = document.getElementById("<%=HiddenField1.ClientID%>");
hiddenField.value = SourceID;
}
</script>
<asp:HiddenField ID="HiddenField1" runat="server" Value="" />
<asp:ImageButton ID="ImageButton1" runat="server" OnClientClick="SetSource(this.id)" />
The Page_Load would then implement by some means:
-VB.NET
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Me.Load
' ...
If Not Page.IsPostBack Then
If Not String.IsNullOrEmpty(Me.Page.Request.Form(Button1.UniqueID)) Then
' ...
ElseIf Not String.IsNullOrEmpty(Me.Page.Request.Form(Button2.UniqueID)) Then
' ...
ElseIf Not Me.Page.Request.Form(HiddenField1.UniqueID) Is Nothing _
And Not String.IsNullOrEmpty(Me.Page.Request.Form(HiddenField1.UniqueID)) Then
' ...
HiddenField1.Value = String.Empty
Else
' ...
End If
End If
End Sub
on page load check this
String ButtonID = Request["__EVENTTARGET"];
Related
I have the following code in ASP.net / VB.
When a button is pressed on the page, the div_yes_no (see code below) popsup as a YesNO message. The popup shows two buttons (YES and NO)
<div id="div_yes_no" class="messagepopup" runat="server">
<br/>
<span class="desc">Are you sure you want to transfer this data (Y/N) ?</span>
<br/>
<asp:Button ID="btnYES" runat="server" Text="Yes" OnClientClick="ShowCoverNONE(''); Hide2();" OnClick="btnYES_Click" CssClass="STD_button" />
<asp:Button ID="btnNO" runat="server" Text="No" OnClientClick="ShowCoverNONE(''); Hide2();" CssClass="STD_button" />
</div>
This is the code in VB which should run when btnYES is clicked:
Protected Sub btnYES_Click(sender As Object, e As EventArgs)
MsgBox("hello")
.... actual code
End Sub
The problem is that the btnYES_Click code is not firing, just the javascript fires: OnClientClick="ShowCoverNONE(''); Hide2();"
Any ideas what's missing and or how to do this a better way?
You can't use the MsgBox("hello") in ASP.NET as you use it in windows forms application. Can you try by removing it?
ASP.Net with VB.NET as Code-behind usualy does not use the OnClick attribute on Buttons. Instead you need to add the Handles-clause with the button's name in your VB.Net Code-behind code. Like this:
Protected Sub btnYES_Click(sender As Object, e As EventArgs) Handles btnYES.Click
MsgBox("hello")
.... actual code
End Sub
Please also look at this page: How to use OnClick and OnClientClick events to Prevent Double Clicking on your ASP.Net Buttons.
Ok, I finally found the answer to this problem. For others in case they encounter the same, the problem was that the code
asp:Button ID="btnYES" runat="server" Text="Yes" OnClientClick="ShowCoverNONE(''); Hide2();" OnClick="btnYES_Click" CssClass="STD_button" />
was NOT within the Ajax ContentTemplate/updatepanel:
</ContentTemplate>
</asp:UpdatePanel>
Once I put it there, it all worked as normal.
I don't know why calling another function inside the OnUploadedComplete does not work in ordinary way, It's my code:
ASP.NET code:
<asp:AsyncFileUpload ID="AsyncFileUpload1" runat="server"
OnUploadedComplete ="UploadFile1"
OnClientUploadComplete="uploadComplete" ThrobberID="myThrobber"
onclientuploaderror="uploadError" CompleteBackColor="White" />
VB.NET code:
Protected Sub UploadFile1(ByVal sender As Object, ByVal e As System.EventArgs)
'saveing file on disk, this part works fine, but calling
'myfunction() does not work properly
myfunction()
End Sub
Sub myfunction()
mylabel.Text="done" 'this does not work
insert_records_to_db() 'this works
End Sub
This is because an AsyncFileUpload-Control is rendered in an IFrame(normally a FileUpload is only possible with full postbacks due to security reasons), therefore it does not have the normal behaviour of UpdatePanels.
You can workaround it by handling the clientside OnClientUploadComplete to trigger a hidden button that causes an asynchronous postback.
OnClientUploadComplete="uploadComplete"
function uploadComplete() {
$get("<%=btnShowUploadResult.ClientID %>").click();
}
<asp:Button ID="btnShowUploadResult" runat="server" CausesValidation="false" Text="hidden" Style="display: none" />
You can store your message in the serverside OnUploadedComplete into a Session variable and read it in btnShowUploadResult.Click handler.
I believe it's due to how the AsyncFileUpload control works, see this for more information.
Couldn't you just use the client side javascript function to change your label text?
I'm using a repeater ListOfArticles and have controls inside it like ddlSizes and btnSelectArticle. Normally you can just double click the control and in the aspx.vb page you can specify an action. I have heard something about Findcontrol, but can't figure out or find much information that I understand. I don't want to sound like an ass, but I would really prefer help for the aspx.vb page and not in C# or Javascript.
An example of what I'm trying to do is, once you've clicked btnSelectArticle the label lblSelection receives the following values Amount: txtAmount - Size: ddlSizes.SelectedValue.
<asp:Repeater ID="rptListOfArticles" runat="server" DataSourceID="objdsArticleList">
<asp:DropDownList ID="ddlSizes" runat="server" AutoPostBack="True" DataSourceID="objdsSizes" DataTextField="SizeName" DataValueField="SizeID" OnSelectedIndexChanged="ddlSizes_SelectedIndexChanged" />
<asp:Button ID="btnSelect" runat="server" Text="Select" OnClick="btnSelect_OnClick" />
<asp:Label ID="lblSelection" runat="server" Text=""></asp:Label>
In the aspx.vb page I can only select this and my controls like ddlSizes and btnSelect aren't recognized.
Protected Sub rptListOfArticles_ItemCommand(ByVal source As Object, ByVal e As System.Web.UI.WebControls.RepeaterCommandEventArgs) Handles rptListOfArticles.ItemCommand
End Sub
Any help towards a solution would be great!
What you need to do is use the FindControl method to find the specific control in the selected repeater Item.
so an example would be (within the ItemCommand method)
Dim lblSelection as Label = CType(e.Item.FindControl("lblSelection"), Label)
lblSelection.Text = "Your Text"
Edit **
To Answer your questions in the comments:
Yes to access the SelectedValue of the ddlSize DropDown you will need to create this:
Dim ddlSize As DropDownList = Ctype(e.Item.FindControl("ddlSize"), DropDownList)
The Repeater will know when to call this method when any Buttons are Clicked within the Repeater. Add a CommandName to your buttons so that you can then control what happens in the ItemCommand method.
e.g.
<asp:Button id="btnDoSomething" runat="server" text="Run ItemCommand" CommandName="Command1" />
In the ItemCommand use the code:
If e.CommandName = "Command1" Then
' run your code
End If
You can handle the event of dropdownlist in ItemCommand Event. Event bubbling concept comes here actually the child control bubble the evenet up to its parent i.e repeater control so you can handle it in parent control event eventually
for more details HERE you will have indepth insight of all events of repeater
I have a page that has several ListBoxes that have some cascading filtering based on the selected values using an AutoPostBack. The form takes all the selected values and generates an excel doc by cross-page posting to a different ASPX. The problem is, after clicking submit once, it will continually fire the cross-page postback every time a selection has changed.
<asp:ScriptManager runat="server" />
<asp:UpdatePanel UpdateMode="Conditional" runat="server">
<ContentTemplate>
<asp:ListBox ID="ParentItems" runat="server" SelectionMode="Multiple" AutoPostBack="true"></asp:ListBox>
<asp:ListBox ID="ChildItems" runat="server" SelectionMode="Multiple" AutoPostBack="true"></asp:ListBox>
</ContentTemplate>
</asp:UpdatePanel>
<asp:Button ID="Submit" runat="server" PostBackUrl="~/AnotherPageThatGeneratesAnExcelDoc.aspx" />
How do I cancel the cross-page postback from the ListBoxes' SelectedIndexChanged events?
Here's the event in the codebehind:
Protected Sub ParentItems_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles ParentItems.SelectedIndexChanged
'' do some filtering of the ChildItems ListBox
'' tried these but they do not work
''Submit.Enabled = False
''Submit.PostBackUrl = String.Empty
'' I also tried wrapping the button in a PlaceHolder and hiding/removing it, neither worked
''Buttons.Visible = False
''Buttons.Controls.Remove(Submit)
End Sub
This is my current solution using javascript. It works, but seems like a hack:
// using jQuery, add a click event that resets the form action
$("select[multiple]").click(function () {
this.form.action = this.form._initialAction;
});
Edit: adding a click event in the codebehind:
ParentItems.Attributes("onclick") = "this.form.action = this.form._initialAction;"
The problem is that using the PostbackUrl property resets the form action to a new URL, and your Ajax calls (or any subsequent postbacks) use whatever the current action of the form is.
Your solution doesn't work because the submit button isn't part of your UpdatePanel, so it never gets modified.
The easiest solution might be to move your Excel file generating code out of the page it's in, and into the page you're looking at, in the click handler of the button.
You also could probably include an iframe on the page you're looking at, and on submit, rather than going to a new page, set the source of the iframe to the Excel-generating page.
Both of these would avoid the need for using the PostbackUrl.
I must be doing something wrong. I can't seem to execute my CustomValidator's ServerValidate method.
I've got a Visual Basic ASP.NET page with a CustomValidator...
<asp:TextBox ID="TextBox1" runat="server" />
<asp:CustomValidator ID="CustomValidator1" runat="server"
ControlToValidate="TextBox1"
ErrorMessage="Friendly message goes here."
Display="Dynamic" />
<asp:Button ID="Button1" runat="server"
Text="Submit"
CausesValidation="True" />
For this test, I've got the validation set to always fail...
Sub CustomValidator1_ServerValidate(ByVal source As Object, ByVal args As System.Web.UI.WebControls.ServerValidateEventArgs) Handles CustomValidator1.ServerValidate
args.IsValid = False
End Sub
But, when the button is clicked, the CustomValidator1_ServerValidate() method never executes!
Protected Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Page.Validate()
If Page.IsValid Then
'it executes the code here!
End If
End Sub
Not even if I explicitly validate that control...
CustomValidator1.Validate() 'does nothing?
What am I doing wrong?
Add the property:
ValidateEmptyText="True"
Are you putting the validator control submit button in the same validation group?
Firstly, You seem to be missing the OnServerValidate attribute in your markup above.
Secondly, I would check to ensure that CustomValidator1_ServerValidate has been set up as an eventhandler for the ServerValidate event for Textbox1. I have had occasions where I have changed the name of the validate method in the markup and code-behind, but the IDE has not auto updated the subscribing method name passed to the eventhandler delegate
I know it's a daft question (or might sound like it!). But have you actually entered or changed the value in the textbox? I think the validator won't trigger without the contents of the textbox changing.