Click here to Skip to main content
15,885,216 members
Articles / Web Development / ASP.NET

Button Tips and Tricks - Part II

Rate me:
Please Sign up or sign in to vote.
4.25/5 (4 votes)
14 Jul 2011CPOL5 min read 22.3K   31   1
In this article, we are going to learn different tips and tricks of asp:Button control.

Introduction

In this article, we are going to learn how to access the CommandArguments of the button, how to fire JavaScript function on click on the Button and prevent the Form submission, how to avoid multiple clicks while submitting the form on the server, how to post a page to another page in ASP.NET, how to specify the Tab index for the TextBox, Button or any other ASP.NET form control, how to specify the Tooltip for the ASP.NET Server controls and how to specify a default button on the page so that when user hits the Enter key, that button gets clicked.

I have written hundreds of ASP.NET, jQuery, HTML, CSS and JavaScript How to Tips and Tricks, click here to get them all.

Let's learn all the above mentioned tips and tricks one by one.

How to Access the CommandArguments of the Button?

In case we want to set optional parameter to the button to determine some values in the server side code, we can use this approach.

CommandArguments is a way to get or set optional parameter to the command events along with CommandName.

ASPX PAGE

ASP.NET
<p><asp:Button ID="Button4" runat="server" Text="Sort in Ascending Order"
CommandName="Sort" CommandArgument="Ascending" OnCommand="SortData" /></p>
<p><asp:Button ID="Button5" runat="server" Text="Sort in Descending Order"
CommandName="Sort" CommandArgument="Descending" OnCommand="SortData" /></p>

CODE BEHIND

C#
protected void SortData(object sender, CommandEventArgs e)
{
   string commandName = e.CommandName;
   if (commandName.Equals("Sort"))
   {
     var commandArguments = e.CommandArgument;
     if (commandArguments.Equals("Ascending"))
     {
       Response.Write("Sort in ascending order");
     }
     else if (commandArguments.Equals("Descending"))
     {
        Response.Write("Sort in descending order");
     }
   }
} 

In the above code snippet, I have specified same CommandName, OnCommand method for both buttons but different CommandArguments. On click of the first button, “Sort in ascending order” is written and on click on second button “Sort in descending order” is written on the page.

How to Fire JavaScript Function on Click on the Button and Prevent the Form Submission?

In case we want to fire a JavaScript function on click on the button and prevent web form
submission, we can use this approach.

ASPX PAGE

ASP.NET
<p><asp:Button ID="btnSubmit" runat="server" UseSubmitBehavior="false"
OnClientClick="return AlertMe()" Text=" Show Alert and Do not submit the form" /></p>
<script language="javascript" type="text/javascript">
function AlertMe() {
    alert("JavaScript function called");
    return false;
   }
</script>

To fire JavaScript function on click event of the asp:Button, we can specify the OnClientClick event of the button to the JavaScript function.

In the above code, I have placed a button with UseSubmitBehavior=false. In most of the browsers, even if we keep UseSubmitBehavior=false, the form is submitted to the server and we will notice a browser refresh. To avoid this, we can place return statement on the OnClientClick event and in the JavaScript function we can return false. Returning false stops the form being submitted to the server.

How to Avoid Multiple Clicks while Submitting the Form on the Server?

In case we want to avoid multiple clicks while submitting the form on the server, we can use this
approach. Generally this is used in case of Payment button or financial application to avoid multiple debit or credit however it can also be used in normal applications to avoid duplicate data
submission.

ASPX PAGE

ASP.NET
<form id="form1" runat="server">
    <div>
        <p>Payment amount: <asp:TextBox ID="txtAmount" runat="server" />
        <asp:RequiredFieldValidator ID="req1" runat="server" Text="*"
        ErrorMessage="Mandatory !" ControlToValidate="txtAmount" />
       </p>
       <p>Description: <asp:TextBox ID="txtDescription" runat="server" /> </p>
       <p><asp:Button ID="btnPay" runat="server" Text="Submit" OnClick="SubmitData"/></p>
    </div>
</form>

CODE BEHIND

C#
protected void Page_Load(object sender, EventArgs e)
{
    // Just disable the button after click
   this.btnPay.Attributes.Add("onclick",
  DisableTheButton(this.Page, this.btnPay));
}
protected void SubmitData(object sender, EventArgs e)
{
    System.Threading.Thread.Sleep(5000);
    Response.Write("Amount: " + txtAmount.Text + " | Description: "+ txtDescription.Text);
}
// ideally you should keep this into any utility class and call it 
// from the page_load event
public static string DisableTheButton(Control pge, Control btn)
{
   System.Text.StringBuilder sb = new System.Text.StringBuilder();
   sb.Append("if (typeof(Page_ClientValidate) == 'function') {");
   sb.Append("if (Page_ClientValidate() == false) { return false; }} ");
   sb.Append("this.value = 'Please wait...';");
   sb.Append("this.disabled = true;");
   sb.Append(pge.Page.GetPostBackEventReference(btn));
   sb.Append(";");
   return sb.ToString();
}

In the above code snippet (aspx), I have two textboxes (Amount and Description). The Amount is mandatory as I have used RequiredFieldValidator with it. I want to avoid a scenario when user can click the Pay button multiple times and the amount will be deducted multiple times (in real scenario).

OUTPUT

26.JPG

To avoid multiple clicks, we can attach JavaScript onclick event from the code behind and in that event we can specify DisableTheButton server side method that basically writes the JavaScript code that ensures that the Submit event only fires when ASP.NET Validation has successfully passed and the page is ready to be submitted.

If the ASP.NET client side validation is passed, the button text is changed to “Please wait …” and it is disabled to make sure that the end user shall not be able to click on this button again and then the normal do Postback events too fires. These normal do Postback events are written because of the GetPostBackEventReference method called in the last but one line in DisableTheButton server side method.

How to Post a Page to Another Page in ASP.NET?

In case we want to post a page to another page in ASP.NET, we can use this approach.

ASPX PAGE

ASP.NET
<p><asp:TextBox ID="txtName" runat="server" /></p>
<p><asp:Button runat="server" Text="Submit to another page" 
	PostBackUrl="~/PosttoAnotherPageResult.aspx" /></p>
<p><asp:LinkButton ID="lnkSubmit" runat="server" 
    Text="Submit to another page" PostBackUrl="~/PosttoAnotherPageResult.aspx" /></p>

To post a page to another page, we can set the PostBackUrl properties of the asp:Button or
asp:LinkButton control.

OUTPUT

Source Page

27.JPG

On the target page, we need to retrieve the previous page Form data using Request.Form object.

CODE BEHIND – TARGET PAGE (POSTTOANOTHERPAGERESULT.ASPX)

C#
protected void Page_Load(object sender, EventArgs e)
{
   if (Request.Form != null)
   {
       Response.Write(Request.Form["txtName"]);
   }
}

Target Page

27b.JPG

How to Specify the Tab Index for the TextBox, Button or any other ASP.NET Form Control?

In case we want to specify the tab index to the control so that when user presses tab he is navigated to different controls (textbox, dropdown) on the page in a sequence, we can use this approach.

ASPX PAGE

ASP.NET
<p><asp:TextBox ID="txtName" runat="server" TabIndex="1" /></p>
<p><asp:TextBox ID="TextBox1" runat="server" TabIndex="3" /></p>
<p><asp:TextBox ID="TextBox2" runat="server" TabIndex="2" /></p>

In the above code, the TabIndex property has been specified to TextBoxes 1, 3 and 2 respectively so if tab key will be pressed from first TextBox, the cursor shall jump to the third TextBox and then on second TextBox.

This applies to the HTML Form controls as well.

How to Specify the Tooltip for the ASP.NET Server Controls?

In case we want to specify tooltip for an ASP.NET server control to give hint to the user about a
particular textbox or dropdown, etc. we can use this approach. Tooltip appears when user mouse over that control.

ASPX PAGE

ASP.NET
<p><asp:TextBox ID="txtName" runat="server" TabIndex="1" 
	ToolTip="Please enter search keyword" /></p>
<p><asp:TextBox ID="TextBox1" runat="server" TabIndex="3" /></p>

OUTPUT

29.JPG

To apply the Tooltip for the button or any other ASP.NET server controls, Tooltip property can be set. As displayed in the above code snippet, I have set “Please enter search keyword” as Tooltip for the first textbox and that is displayed as tooltip to the end user when he/she mouse over it.

How to Specify a Default Button on the Page so that When User Hits the Enter Key, that Button Gets Clicked?

In case we have multiple buttons on the data entry page and we want to specify a default button so that when user hits enter key after entering data, that button gets clicked automatically, we can use this approach.

ASPX PAGE

ASP.NET
<form id="form1" runat="server" defaultbutton="Button5">
   <div>
     <p><asp:TextBox ID="txtName" runat="server" TabIndex="1" 
	ToolTip="Please enter search keyword" /></p>
    <p><asp:TextBox ID="TextBox1" runat="server" TabIndex="2" /></p>
    <p><asp:Button ID="Button1" runat="server" Text="Button 1" 
	OnClick="SubmitData" CommandName="Command1" />
    <asp:Button ID="Button2" runat="server" Text="Button 2" 
	OnClick="SubmitData" CommandName="Command2" />
    <asp:Button ID="Button3" runat="server" Text="Button 3" 
	OnClick="SubmitData" CommandName="Command3" />
    <asp:Button ID="Button4" runat="server" Text="Button 4" 
	OnClick="SubmitData" CommandName="Command4" />
    <asp:Button ID="Button5" runat="server" Text="Submit" 
	OnClick="SubmitData"  CommandName="Command5" /></p>
  </div>
</form>

CODE BEHIND

C#
protected void SubmitData(object sender, EventArgs e)
{
   Button btn = (Button)sender;
   Response.Write(btn.CommandName);
}

To specify the default button, we can specify the defaultbutton attribute of the Form element. In the above code snippet, we have 5 buttons and we have specified defaultbutton to “Button5” so the 5th button shall be active and when use hits enter key after entering the data into the form the 5th button fires. As we have attached SubmitData method to all 5 buttons (you can attach different methods as well) so the same method fires on click of every button and write its CommandName on the page.

OUTPUT

30.JPG

Read the first part of this Button Tips and Tricks here.

Thanks for reading! Do let us know your feedback.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Web Developer ITFunda
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionStrange Pin
Richard MacCutchan14-Jul-11 4:29
mveRichard MacCutchan14-Jul-11 4:29 
I tried to respond to your other messages but they were connected to the deleted article so it was not possible. It seems that there is still something wrong with your images or the links. I suggest you post a message in the Site Bugs & Suggestions forum, so Chris can take a look for you.
The best things in life are not things.

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.