Setting focus onto another contol from button click - c#

I am using ASP.NET 2.0 and VB.NET (C# code will also help me out)
On top of my page I have a button called btnViewRecords. When the User click on the button I want to set focus to another button or label further down on the same page. How can this be done.
This code does not work for me..............
btnTheRecords.Focus()
or
lblHeader.Focus()
Thanks in advance!!
Edit:
Even if my code did work, i dont want to reload the page every time.

Here's a relatively simple solution...
<asp:Button ID="Button1" runat="server" Text="Button"
OnClientClick="return SetFocus()" />
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
<script type="text/javascript">
function SetFocus() {
document.getElementById('<%=TextBox2.ClientID %>').focus();
//or this if you're using jQuery
//$("#<%=TextBox2.ClientID %>").focus();
return false;
}
</script>

You can use JavaScript to do this.
document.getElementById ( "btnTheRecords" ).focus();
By setting focus what do you mean. Do you want to bring this control into view if it is way down the page. Then there are better ways to do this.
Edit:
You can place an anchor tag near the button or the bale and set
location.href = "#anchorId";
where anchorId is the id of the anchor tag.
will move the focus to the anchor tag.

Try this,
I wrote a small code and it seems to be working for me. sorry this is in C# but if you click on a button and set focus on another button then page will automatically scroll down for you.
ASP.NET
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_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">
<div>
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
</div>
<div style="height:50px;"></div>
<div>
<asp:Button ID="Button1" runat="server" Text="Button 1" onclick="Button1_Click" />
</div>
<div style="height:1000px;"></div>
<div>
<asp:Button ID="Button2" runat="server" Text="Button 2" onclick="Button2_Click" />
</div>
</form>
</body>
</html>
AND Code Behind
using System;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
Button2.Focus();
Label1.Text = "button1 clicked & button2 in focus";
}
protected void Button2_Click(object sender, EventArgs e)
{
Button1.Focus();
Label1.Text = "button2 clicked & button1 in Focus";
}
}

I'm not sure exactly of the problem you're having. But in cases where the SetFocus() function and such just don't work (and they often don't in VB for some reason). I've often used workarounds such as shortcut Keys & mnemonics in combination with SendKeys() to get focus where I need it to be.
Depending on whether the buttons you are talking about are in your ASP.NET code or in your VB.NET code, this may be a viable workaround for you as well.

document.getElementById("spanId").scrollIntoView(false)
Reference:
.scrollIntoView

If the button is server side, set the "OnClientClick"
action on it to a javascript function. Cancel windows
events so the page location does not change.
function goto(){
window.event.cancelBubble = true;
window.event.returnValue = false;
document.getElementById("pageloction").focus()
}
asp:Button runat="server" ID="btnTheRecords" OnClientClick="javascript:goto()" />
span id="pageloction">

Related

Button_Click method no longer works

I am modifying a large (11 page) web form that I inherited from a previous employee. I am new at ASP and HTML5, etc. I modified many lines of code, but I haven't touched the button code in either HTML or C#. The Button_Click method used to work, in that clicking the button would run the form validation code and the data saving code. Here is the HTML:
<div style="position: relative; float: right">
<asp:Button ID="Button1" runat="server" Text="Submit" OnClick="Button1_Click" class="btn btn-primary" />
</div>
And here is the code-behind for Button_Click:
protected void Button1_Click(object sender, EventArgs e)
{
if (ValidationForm())
{
SaveData();
}
}
I put breakpoints inside Button1_Click and the function is never entered. Is there another way to debug to see what's going on?
Here's the top of the aspx page:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="default.aspx.cs" Inherits="smacklabProject._default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
...
I have not changed the inherits. I don't even know what inherits does.
Here's the top of the aspx.cs (below using):
namespace smacklabProject
{
public partial class _default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
if (ValidationForm())
{
SaveData();
}
}
private void SaveData()
{
string study = Study_Dropdown.SelectedValue;
...
OK this happened to me once.
So if you're using visual studio, click the button at the top that has the start sign to run it and start debugging.
If you run it by right-clicking it from the solution explorer and selecting the view in browser option, it would not consider the back-end code.
I can't comment yet Sadly that's why i had to post this as an answer.
A co-worker solved the problem for me. There was a hidden text box that had a range validator and a default value that was outside of the range. So it would always fail validation, but the failure text was hidden.
For reference, never do this:
<p>
<asp:RangeValidator runat="server" ID="RangeValidator1" ControlToValidate="IPAQ_Q2_Days" MinimumValue="1" MaximumValue="7" Type="Double" Text="The value must be from 1 to 7" Font-Size="Large" ForeColor="Red" />
</p>
<asp:Label ID="IPAQ_Q2_Days_Label" AssociatedControlID="IPAQ_Q2_Days" ForeColor="White" Font-Size="11" Font-Weight="Normal" Text="Please indicate the number of days you performed vigorous activities at work." runat="server">
<asp:TextBox ID="IPAQ_Q2_Days" runat="server" class="form-control" placeholder="___ days per week" Width="200" value="0"></asp:TextBox>
</asp:Label>

I am unable to cancel an ASP.NET page

I am new to web programming. I have a pretty standard page that accepts contact information and I am trying to add validation controls to it. When the user clicks the cancel button nothing is saved so I just want to unload the page and go back to the previous page. My problem is, even the the cancel button has CausesValidation="false the validation events are still firing and a post back does not occur. I am using Visual Studio 2012 and C#. I've created a test page to reduce the code I'm working with to the minimum required code to demonstrate the issue. I have tried the javascript disableValidation() function with both Page_Validation = false; and the loop to disable the individual validation controls without success. When I check Page_Validation it is false, and the loop throws the exception Page_Validators is undefined.
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="TestMe.aspx.cs" Inherits="ElmoWeb.TestMe" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
<title>Simple Little Test Form</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="uxEmail" runat="server" placeHolder="email address" type="email" AutoCompleteType="Email"></asp:TextBox>
<asp:RegularExpressionValidator ID="uxEmailValidator" runat="server"
ControlToValidate="uxEmail"
ValidationExpression="^[a-zA-Z][\w\._%+-]*[a-zA-Z0-9]#[a-zA-Z0-9][\w\.-]*[a-zA-Z0-9]\.[a-zA-Z][a-zA-Z\.]*[a-zA-Z]$"
ErrorMessage="The email address is invalid"
EnableClientScript="false" ValidationGroup="testing"
Display="Static"/>
</div>
<div>
<asp:Button ID="Submit" runat="server" Text="Submit" CausesValidation="true" UseSubmitBehavior="true" ValidationGroup="testing" />
<asp:Button ID="Cancel" runat="server" Text="Cancel" CausesValidation="false" UseSubmitBehavior="true" ValidationGroup="FakeValidationGroup" />
</div>
<div>
<asp:ValidationSummary ID="ValidationSummary1" runat="server" DisplayMode="List" HeaderText="You must correct the following errors." ValidationGroup="testing" />
</div>
</form>
</body>
</html>
Currently the code behind just writes a message to the output window so I can see if the post back occurred.
protected void Page_Load(object sender, EventArgs e)
{
System.Diagnostics.Debug.WriteLine("TextMe.aspx Page_Load event, sender = " + sender.ToString() + ", EventArgs = " + e.ToString());
}
The natural way of solving issues where two or more submit buttons should behave in a different way is to use validation groups.
A validation group is set with the ValidationGroup attribute on both a submit button and a group of validators. The same value binds a button and validators and only validators with the same value of the attribute fire when the button is clicked.
In your case, setting the ValidationGroup on the accept button and your validators to "Accept" and leaving the default (empty) value on the cancel button would solve your issue. This is much simpler than any of the workarounds you tried.

.toggle() a div with asp:button

I have a basic div that I want to .toggle() OnClientClick of an asp:button. It works as far as the code goes but I think that the OnClick event handler on the server side is causing the div to reset after it is clicked. Basically what happens is the div disappears for about .01ms and then reappears right away. Here is the simplest code example of my problem.
Here is an example of what happens:
Default.aspx:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication2.Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Testing</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script type="text/javascript">
function ToggleMe() {
$('#toggleMe').toggle();
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div id="toggleMe">
<label>Hello World</label>
</div>
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" OnClientClick="ToggleMe();"/>
</form>
</body>
</html>
Default.aspx.cs
using System;
namespace WebApplication2
{
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
int i = 5;
}
}
}
I have tried .removeClass, .addClass, .css... I don't think it's as much an issue with the jQuery that I am using as it is with the postback that happens on the button click.
I am running Chrome to test this if that matters.
Thanks in advance for your time and help!
The javascript part of your HTML executes in the user's browser. The protected void button1_click method executes on the server. What is happening is that the user's browser will toggle the div correctly, causing it to disappear. Unfortunately, the HTML of the ASP.NET button will then resubmit the page, meaning the browser refreshes the HTML from your server. The server has no concept of the toggle happening because the javascript did not execute there, and while int i is set to 5, the div gets re-set to being visible after the page refreshes after going to your server. Your options are:
1) don't use any server side logic for the button click, and get rid of
<asp:Button ID="Button1" ... />
and replace it with
<input type="button" onclick="ToggleMe();">your text</input>
and handle all of your client side logic in your javascript. If you need to set int i = 5 on the server, use JQuery.Ajax to talk back to the server.
2) use only server side .NET to do this. This is implemented like so:
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Testing</title>
</head>
<body>
<form id="form1" runat="server">
<div id="toggleMe" runat="server">
<label>Hello World</label>
</div>
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
</form>
</body>
</html>
And
protected void Button1_Click(object sender, EventArgs e)
{
int i = 5;
toggleMe.Visible = !toggleMe.Visible;
}
when u click the aspx:Button, it submits the page. it is much easier if you use regular html button
<input type="button" onclick="ToggleMe()">Button</input>
and please add a "return false;" statement to your code below
function ToggleMe() {
$('#toggleMe').toggle();
return false;
}

Adding OnClick event to ASP.NET control

i would like to create OnClick event for my panel. So far now the most of the google results look more or less like this: adding onclick event to aspnet label. Is there any way, to call codebehind function from javascript or panel attributes? Because I would like to Redirect user to a new page and before that save some information in ViewSTate or Sessionstate. Any suggestions?
In your java script method raise a __dopostback call to a Server side method.
<script type="text/javascript">
function YourFunction()
{
__doPostBack('btnTemp', '')
}
</script>
Where btnTemp is a server side button, so write a onClick event of this button on server side, where you can do the processing and then redirect to other page.
You can have a good understanding of dopostback at DoPostBack Understanding
My aspx page is like:
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<script type="text/javascript">
function CallMe() { __doPostBack('btnTemp', '') }
</script>
</head>
<body>
<form id="form1" runat="server">
<asp:Button ID="btnTemp" runat="server" Text="Test" onclick="btnTemp_Click" />
<div> <asp:Label ID="Label1" runat="server" Text="Label1"></asp:Label>
<asp:Label ID="Label2" runat="server" Text="Label"></asp:Label></div>
</form>
</body>
And my Server Side code is as:
protected void Page_Load(object sender, EventArgs e)
{
Label1.Attributes.Add("onClick", "CallMe();");
}
protected void btnTemp_Click(object sender, EventArgs e)
{
}
Thats the code that I have written, I haven;t included the using statement, Page directive etc in above code.
There is a PostBackUrl property on a ASP.NET Button, you could render the button as normal then postback to a different page - this is where your OnClick method would need to be declared.
I would strongly recommend against posting back to the same page then doing a Response.Redirect(), consider the traffic. The browser requests the page, posts back then is sent a HttpRedirect and then navigates to the new page. With the method I have outlined above this is not required and the browser has to make one request less (meaning the message doesn't have to be sent or the page rebuilt on the server) and is a significant performance benefit.

Why IE does not refresh the page after a JS call to a click button?

On a ASP.Net page, I am in front of a problem only with IE. Here is the description.
On a page, there is two buttons and one label. The first button is visible and calls a JS function on the click event. This JS function calls the click function of the second button. The second button has an C€ event handler on the click event. The C# event handler edit the label.
In Firefox : the label is correctly edited after the clicks.
In IE (8) : the label is not edited, despite the C€ event handler has been correctly hit.
Also, I observed, in IE, that the Page_Load event is called two times after the JS button click :
Page_Load
button2_OnClick => change of the Label Text
Page_Load => The Label Text is reset :(
In Firefox, the Page_Load is called only once.
My question is : how to make IE refresh correctly the page as Firefox does after a JS button click ?
Below is the sample test code :
1) Page ASPX
<head runat="server">
<title></title>
<script type="text/javascript">
function button1Click(sender, args) {
var button2 = document.getElementById("button2");
button2.click();
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button runat="server" ID="button1" Text="Click-me!" OnClientClick="button1Click();" />
<asp:Button runat="server" ID="button2" Text="Second" OnClick="button2_OnClick" style="display:none" />
<p />
<asp:Label runat="server" ID="label1" Text="Init" />
</div>
</form>
</body>
</html>
2) C# code-behind :
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void button2_OnClick(object sender, EventArgs e)
{
label1.Text = "Changed";
}
}
The ID of your button will not be button1 or button2 when it's rendered. It will probably be something like ctl001_button1. Therefore your javascript will not work. In ASP.NET 4 you can override this behaviour by using an assigned ClientID.
<asp:Button runat="server" ID="button1" Text="Click-me!"
OnClientClick="button1Click();" ClientIDMode="Static" />
<asp:Button runat="server" ID="button2" Text="Second"
OnClick="button2_OnClick" style="display:none" ClientIDMode="Static" />
As an aside, this alludes to the main problem with ASP.NET Winforms - it tricks developers into thinking that the web is a connected environment.
What actually happens when you click an <asp:Button /> element by default is that a postback is invoked. I.e. Your browser sends a request to the server for a new page. It sends up something called ViewState which is how the server knows what you've done and what to render. There is no "event" handled as such.
I think the problem is with the way you are trying to get the hidden button
var button2 = document.getElementById("button2");
maybe change this to
var button2 = document.getElementById("<%= button2.ClientID %>");
After the buttons are rendered in the browser, the ID is changed by the ASP.Net engine, and not the same as your source.
http://msdn.microsoft.com/en-us/library/system.web.ui.control.clientid.aspx
Hope this helps.

Categories

Resources